Bird
Raised Fist0
Interview Preptwo-pointersmediumGoogleAmazonFacebook

Minimum Difference Between K Closest Elements

Choose your preparation mode4 modes available
▶
Steps
setup

Start with the original array

We begin with the unsorted input array and the given K value. No operations have been performed yet.

💡 Seeing the original array helps you understand why sorting is necessary before sliding the window.
Line:arr = [10, 12, 10, 7, 5, 22] k = 3
💡 The array is unsorted, so direct sliding windows won't work correctly.
📊
Minimum Difference Between K Closest Elements - Watch the Algorithm Execute, Step by Step
Watching each step helps you understand how sorting and sliding windows work together to efficiently find the minimum difference among K elements without checking all subsets.
Step 1/16
·Active fill★Answer cell
setup
10
0
12
1
10
2
7
3
5
4
22
5
Result: "∞"
setup
5
0
7
1
10
2
10
3
12
4
22
5
Result: "∞"
setup
5
0
7
1
10
2
10
3
12
4
22
5
Result: "∞"
traverse
i
5
0
7
1
10
2
10
3
12
4
22
5
Result: "∞"
compare
i
5
0
7
1
10
2
10
3
12
4
22
5
Result: "∞"
insert
i
5
0
7
1
10
2
10
3
12
4
22
5
Result: 5
move_right
5
0
i
7
1
10
2
10
3
12
4
22
5
Result: 5
compare
5
0
i
7
1
10
2
10
3
12
4
22
5
Result: 5
insert
5
0
i
7
1
10
2
10
3
12
4
22
5
Result: 3
move_right
5
0
7
1
i
10
2
10
3
12
4
22
5
Result: 3
compare
5
0
7
1
i
10
2
10
3
12
4
22
5
Result: 3
insert
5
0
7
1
i
10
2
10
3
12
4
22
5
Result: 2
move_right
5
0
7
1
10
2
i
10
3
12
4
22
5
Result: 2
compare
5
0
7
1
10
2
i
10
3
12
4
22
5
Result: 2
prune
5
0
7
1
10
2
i
10
3
12
4
22
5
Result: 2
reconstruct
5
0
7
1
10
2
10
3
12
4
22
5
Result: 2

Key Takeaways

✓ Sorting the array is essential to efficiently find the minimum difference among K elements.

Without sorting, you'd have to check all subsets, which is much slower and harder to visualize.

✓ Sliding a fixed-size window over the sorted array lets us consider only consecutive elements, reducing complexity.

This approach leverages the sorted order to avoid redundant checks and find the answer quickly.

✓ Tracking and updating the minimum difference at each step shows how the algorithm narrows down the best candidate.

Seeing min_diff update visually helps understand the pruning of worse candidates.

Practice

(1/5)
1. Consider the following Python function implementing the optimal approach for counting triplets with sum smaller than target. What is the returned value when calling threeSumSmaller([-2, 0, 1, 3], 2)?
easy
A. 2
B. 3
C. 1
D. 4

Solution

  1. Step 1: Sort input and initialize variables

    Sorted array is [-2, 0, 1, 3], count=0, n=4.
  2. Step 2: Iterate and count triplets

    For i=0 (-2), check if sum of first three elements >= 2? -2+0+1= -1 < 2, continue. Use two pointers left=1, right=3. - curr_sum = -2 + 0 + 3 = 1 < 2 -> count += 3-1=2, left=2 - curr_sum = -2 + 1 + 3 = 2 not < 2 -> right=2 Now left=2, right=2 ends loop. For i=1 (0), sum of nums[1]+nums[2]+nums[3] = 0+1+3=4 >= 2 -> break loop. Total count=2.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Matches expected output from example [OK]
Hint: Count increments by right-left when sum < target [OK]
Common Mistakes:
  • Off-by-one in counting pairs
  • Not breaking early when minimal sum >= target
  • Misusing pointers leading to wrong counts
2. Consider the following code snippet implementing the Dutch National Flag algorithm. Given the input array [2, 0, 1], what is the value of mid after the first swap operation inside the while loop?
easy
A. 3
B. 2
C. 0
D. 1

Solution

  1. Step 1: Trace initial pointers and first iteration

    Initially, low=0, mid=0, high=2, nums=[2,0,1]. Since nums[mid]=2, swap nums[mid] and nums[high]: swap nums[0] and nums[2]. Array becomes [1,0,2], high=1, mid remains 0.
  2. Step 2: Value of mid after first swap

    After swapping 2 and 1, mid is not incremented and remains 0.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    mid does not increment after swapping 2, so mid=0 after first swap [OK]
Hint: mid increments only after swapping 0 [OK]
Common Mistakes:
  • Assuming mid increments after swapping 2
  • Off-by-one on mid pointer
  • Confusing low and mid increments
3. The following code attempts to implement the Dutch National Flag algorithm but contains a subtle bug. Identify the line causing the bug.
medium
A. Line where mid is incremented after swapping 0
B. Line where low is incremented
C. Line where mid is incremented after encountering 1
D. Line where high is decremented after swapping 2

Solution

  1. Step 1: Identify pointer updates after swapping 0

    After swapping nums[low] and nums[mid] when nums[mid]==0, both low and mid must be incremented to avoid infinite loops or incorrect ordering.
  2. Step 2: Locate missing increment

    The code increments low but does not increment mid after swapping 0, causing mid to stay at the same index and potentially reprocessing the same element indefinitely.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing mid increment after swapping 0 causes infinite loop or wrong output [OK]
Hint: mid must increment after swapping 0 to progress [OK]
Common Mistakes:
  • Forgetting mid increment after swap
  • Confusing pointer roles
  • Incrementing mid after swapping 2
4. Suppose the 4Sum problem is modified so that elements can be reused multiple times in quadruplets (i.e., indices can repeat). Which modification to the optimal hash map approach correctly handles this variant?
hard
A. Remove the index overlap check and allow all pairs to combine freely.
B. Use the same hash map approach but skip sorting the array to allow duplicates.
C. Modify the pair combination step to allow pairs with overlapping indices and remove index checks, but ensure quadruplets are sorted and unique.
D. Switch to brute force four nested loops since hash map approach cannot handle reuse.

Solution

  1. Step 1: Understand reuse means indices can repeat

    Index overlap check must be removed or relaxed to allow repeated elements.
  2. Step 2: Adjust pair combination logic

    Allow pairs with overlapping indices but still sort quadruplets and use a set to avoid duplicates.
  3. Step 3: Evaluate other options

    Removing sorting breaks duplicate handling; brute force is inefficient; simply removing checks without sorting leads to duplicates.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Allow index overlap but keep sorting and deduplication [OK]
Hint: Allow index overlap but keep sorting and deduplication [OK]
Common Mistakes:
  • Removing sorting causes duplicates
  • Assuming brute force is only solution
5. Suppose the input array is no longer sorted but you still need to return the squares of each number in sorted order. Which of the following approaches is correct and efficient?
hard
A. Square each element and then sort the resulting array using a standard sorting algorithm.
B. Use a max-heap to insert squares and extract them in sorted order.
C. Use the two-pointer approach from ends, as it works regardless of input order.
D. Modify the input array in place by squaring and then perform an in-place merge sort.

Solution

  1. Step 1: Recognize input is unsorted

    Two-pointer approach relies on sorted input; it fails if input is unsorted.
  2. Step 2: Choose a correct approach

    Squaring then sorting with a standard sort is correct and efficient (O(n log n)) for unsorted input.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting after squaring handles unsorted input correctly [OK]
Hint: Two-pointer requires sorted input; else sort after squaring [OK]
Common Mistakes:
  • Applying two-pointer on unsorted input
  • Using complex data structures unnecessarily
  • Assuming in-place modifications preserve order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard