Bird
Raised Fist0
Interview Preptwo-pointersmediumGoogleAmazonFacebook

Minimum Difference Between K Closest Elements

Choose your preparation mode4 modes available
</>
IDE
def min_diff_brute_force(arr: list[int], k: int) -> int:public int minDiffBruteForce(int[] arr, int k)int minDiffBruteForce(vector<int> &arr, int k)function minDiffBruteForce(arr, k)
def min_diff_brute_force(arr, k):
    # Write your solution here
    pass
class Solution {
    public int minDiffBruteForce(int[] arr, int k) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int minDiffBruteForce(vector<int> &arr, int k) {
    // Write your solution here
    return 0;
}
function minDiffBruteForce(arr, k) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Returning 0 for all inputs without computing difference, especially when K > 1.✅ Compute difference only for windows of size K after sorting; do not shortcut to 0 unless K=1 or all elements equal.
Wrong: max(arr) - min(arr)Taking difference over entire array instead of subsets of size K.✅ Use sliding window of size K on sorted array to find minimal difference, not full array range.
Wrong: IndexError or crashNot handling empty array or K > n cases properly.✅ Add base cases to return 0 or handle invalid inputs gracefully.
Wrong: Incorrect difference due to off-by-one window sizeSliding window loops not iterating correctly over all valid windows.✅ Iterate from i=0 to n-k inclusive to cover all windows of size K.
Wrong: TLEUsing brute force subset enumeration instead of sorting + sliding window.✅ Implement sorting and sliding window approach to achieve O(n log n) time.
✓
Test Cases
t1_01basic
Input{"arr":[5,7,10,10,12,22],"k":3,"n":6}
Expected2

The subset [10, 10, 12] has max-min = 12-10 = 2, which is the smallest possible difference for any 3 elements.

t1_02basic
Input{"arr":[1,5,9,12,15],"k":2,"n":5}
Expected3

The subset [9, 12] has max-min = 12-9 = 3, which is the smallest difference for any 2 elements.

t2_01edge
Input{"arr":[],"k":1,"n":0}
Expected"inf"

Empty array means no elements; minimal difference is 0 by definition.

t2_02edge
Input{"arr":[42],"k":1,"n":1}
Expected0

Single element subset difference is always 0.

t2_03edge
Input{"arr":[5,5,5,5,5],"k":3,"n":5}
Expected0

All elements equal, so difference is always 0 regardless of subset.

t2_04edge
Input{"arr":[-3,-1,0,2,4],"k":2,"n":5}
Expected1

Minimal difference is 1 between pairs like (-1, 0) or (0, 2).

t3_01corner
Input{"arr":[1,2,100,101,102],"k":3,"n":5}
Expected2

The subset [100, 101, 102] has max-min = 102-100 = 2, smaller than subsets including 1 or 2.

t3_02corner
Input{"arr":[-10,-5,0,5,10],"k":2,"n":5}
Expected5

Minimal difference is 5 between pairs like (-10, -5) or (0, 5).

t3_03corner
Input{"arr":[1,3,6,10,15],"k":4,"n":5}
Expected9

Subset [3, 6, 10, 15] has max-min = 15-6 = 9, minimal among all 4-element subsets.

t4_01performance
Input{"arr":[1000000,1000001,1000002,1000003,1000004,1000005,1000006,1000007,1000008,1000009,1000010,1000011,1000012,1000013,1000014,1000015,1000016,1000017,1000018,1000019,1000020,1000021,1000022,1000023,1000024,1000025,1000026,1000027,1000028,1000029,1000030,1000031,1000032,1000033,1000034,1000035,1000036,1000037,1000038,1000039,1000040,1000041,1000042,1000043,1000044,1000045,1000046,1000047,1000048,1000049,1000050,1000051,1000052,1000053,1000054,1000055,1000056,1000057,1000058,1000059,1000060,1000061,1000062,1000063,1000064,1000065,1000066,1000067,1000068,1000069,1000070,1000071,1000072,1000073,1000074,1000075,1000076,1000077,1000078,1000079,1000080,1000081,1000082,1000083,1000084,1000085,1000086,1000087,1000088,1000089,1000090,1000091,1000092,1000093,1000094,1000095,1000096,1000097,1000098,1000099],"k":50000,"n":100000}
⏱ Performance - must finish in 2000ms

Large input with n=100000 and k=50000 tests O(n log n) sorting + O(n) sliding window performance within 2 seconds.

Practice

(1/5)
1. You are given an integer array and asked to find all unique triplets that sum to zero. Which approach guarantees an optimal solution in terms of time complexity and handles duplicates efficiently?
easy
A. Sort the array, fix one element, and use a two-pointer approach to find pairs that sum to the negative of the fixed element, skipping duplicates.
B. Use a greedy approach by sorting and picking the smallest and largest elements to form triplets.
C. Use dynamic programming to build up solutions for smaller subsets and combine them to find triplets.
D. Use three nested loops to check all triplets and store unique sorted triplets in a set.

Solution

  1. Step 1: Understand problem constraints

    We need all unique triplets summing to zero, efficiently handling duplicates.
  2. Step 2: Identify approach that handles duplicates and optimizes search

    Sorting and fixing one element allows using a two-pointer approach to find pairs summing to the complement, skipping duplicates efficiently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting + two-pointer approach is O(n^2) and handles duplicates [OK]
Hint: Sorting + two-pointer handles duplicates and runs in O(n²) [OK]
Common Mistakes:
  • Thinking brute force is optimal
  • Using DP which doesn't fit this problem
  • Greedy approach misses some triplets
2. You are given an array containing only three distinct values representing colors: 0, 1, and 2. The goal is to sort the array so that all 0s come first, followed by all 1s, then all 2s. Which algorithmic approach guarantees an optimal in-place solution with a single pass through the array?
easy
A. Dutch National Flag algorithm using three pointers to partition the array in one pass
B. Standard quicksort partitioning with recursive calls to sort the entire array
C. Counting sort by first counting occurrences then overwriting the array in multiple passes
D. Dynamic programming to track subproblems of sorted prefixes

Solution

  1. Step 1: Understand problem constraints

    The array contains only three distinct values (0, 1, 2), so a specialized approach can be used instead of general sorting.
  2. Step 2: Identify optimal approach

    The Dutch National Flag algorithm uses three pointers (low, mid, high) to partition the array in a single pass with O(n) time and O(1) space, which is optimal.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Counting sort is two-pass, quicksort is O(n log n), DP is unnecessary [OK]
Hint: Three pointers solve this in one pass [OK]
Common Mistakes:
  • Thinking counting sort is one-pass
  • Using quicksort for fixed small domain
  • Confusing DP with sorting
3. You are given a string and need to determine if it reads the same forwards and backwards, ignoring case and non-alphanumeric characters. Which approach guarantees an optimal O(n) time and O(n) space solution for this problem?
easy
A. Reverse the original string and compare it directly to the input string without any preprocessing.
B. Use dynamic programming to check all substrings for palindrome properties.
C. Use a greedy approach to skip characters that don't match and try to fix mismatches on the fly.
D. Preprocess the string by removing non-alphanumeric characters and converting to lowercase, then use two pointers from opposite ends to compare characters.

Solution

  1. Step 1: Understand problem constraints

    The problem requires ignoring case and non-alphanumeric characters, so direct comparison or naive reversal won't work correctly.
  2. Step 2: Identify approach that handles preprocessing and efficient comparison

    Preprocessing to clean the string and then using two pointers from opposite ends ensures O(n) time and space, and correctly handles all cases.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Preprocessing + two pointers is standard for palindrome checks ignoring punctuation [OK]
Hint: Preprocess then two pointers is optimal palindrome check [OK]
Common Mistakes:
  • Trying to compare original string directly without cleaning
  • Using DP which is overkill and slower
  • Greedy skipping mismatches leads to incorrect results
4. What is the space complexity of the recursive two-pointer approach to reverse a string of length n, and why might some candidates incorrectly think it is O(1)?
medium
A. O(1) because the swaps are done in-place without extra arrays.
B. O(log n) because recursion divides the problem in half each call.
C. O(n) because the recursion stack can grow up to n/2 calls.
D. O(n) because a new array is created to hold reversed characters.

Solution

  1. Step 1: Analyze recursion stack usage

    Each recursive call processes one pair of characters, so maximum recursion depth is about n/2, leading to O(n) stack space.
  2. Step 2: Understand why O(1) is incorrect

    Although swaps are in-place, recursion adds call frames on the stack, which consume O(n) space.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Recursion stack depth proportional to input size, so space is O(n) [OK]
Hint: Recursion stack adds O(n) space despite in-place swaps [OK]
Common Mistakes:
  • Ignoring recursion stack space
  • Confusing in-place with constant space
  • Assuming recursion halves problem size each call
5. If the problem changes so that the same element can be used multiple times to reach the target sum (i.e., elements can be reused), which approach correctly solves the problem?
hard
A. Use the two pointers approach moving inward, but allow pointers to stay if sum < target to reuse elements.
B. Use a modified binary search that allows searching from the current index (not i+1) to reuse elements.
C. Use a dynamic programming approach to find combinations allowing repeated elements.
D. Use the brute force nested loops but break early when sum exceeds target.

Solution

  1. Step 1: Understand reuse requirement

    Allowing reuse means pairs can include the same element multiple times, which breaks two-pointer and binary search assumptions.
  2. Step 2: Identify suitable approach

    Dynamic programming can handle combinations with repeated elements efficiently, unlike two pointers or binary search.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DP handles repeated elements and target sums correctly [OK]
Hint: Reuse -> DP for combinations, not two pointers or binary search [OK]
Common Mistakes:
  • Trying to reuse pointers incorrectly
  • Modifying binary search without correctness
  • Assuming brute force is efficient
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