861590. Minimize the Difference

Medium

Minimize the Difference

Slug: minimize-the-difference

Difficulty: Medium

Id: 861590

Topic Tags: Map, Arrays, Data Structures

Company Tags: None

Summary

Given an array arr of integers and a positive integer k, find the minimum difference between any two elements in the array that are at least k apart. In other words, for each element x in the array, we need to find another element y such that |x-y| is minimized and the distance between them (i.e., |x-y|) is at least k. This problem involves manipulating arrays and using data structures like maps to optimize our solution.

Detailed Explanation

To solve this problem, we can iterate through the array and maintain a map of elements with their indices. For each element, we find the minimum difference between it and any other element that is at least k apart from it. We keep track of the minimum difference found so far and return it as our result.

Here's the step-by-step breakdown:

  1. Initialize an empty map indexMap to store elements with their indices.
  2. Iterate through the array arr.
  3. For each element x in the array, find all elements y such that |x-y| >= k. We can use our map indexMap to efficiently look up these elements.
  4. Calculate the minimum difference between x and any of these elements y and update our global minimum difference if necessary.
  5. Return the global minimum difference found.

Time complexity: O(n), where n is the size of the array, since we're iterating through the array once and looking up elements in our map at most twice (once for each element). Space complexity: O(n), as we're storing all elements with their indices in our map.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public int minimizeTheDifference(int[] arr, int k) {
    Map<Integer, Integer> indexMap = new HashMap<>();
    for (int i = 0; i < arr.length; i++) {
        indexMap.put(arr[i], i);
    }
    
    int minDiff = Integer.MAX_VALUE;
    for (int x : arr) {
        int lowerBound = Math.max(0, x - k);
        int upperBound = x + k;
        
        for (int y = lowerBound; y <= upperBound; y++) {
            if (!indexMap.containsKey(y)) continue;
            int diff = Math.abs(x - y);
            minDiff = Math.min(minDiff, diff);
        }
    }
    
    return minDiff;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.