Bird
Raised Fist0
Interview Preptop-k-elementshardGoogleAmazon

Find K-th Smallest Pair Distance

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

int smallestDistancePair(vector<int>& nums, int k) {
    // Write your solution here
    return 0;
}
function smallestDistancePair(nums, k) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 2Greedy approach picking next smallest pair distance directly without binary search.✅ Implement binary search on distance with two-pointer counting to find k-th smallest distance.
Wrong: non-zero for identical elementsFailing to detect all elements equal and returning incorrect distance.✅ Check if max(nums) == min(nums) and return 0 immediately.
Wrong: IndexError or crashNot handling empty or single-element arrays properly.✅ Add guard clauses to return 0 if nums length < 2.
Wrong: Wrong k-th smallest due to off-by-one in counting pairsCounting pairs with distance < mid instead of <= mid in binary search.✅ Count pairs with distance <= mid to correctly narrow binary search.
Wrong: TLE on large inputUsing brute force O(n^2) approach for large n.✅ Use binary search on answer with two-pointer counting for O(n log n + n log W).
✓
Test Cases
t1_01basic
Input{"nums":[1,1,3],"k":1}
Expected0

All pairs are (1,3) distance 2, (1,1) distance 0, (3,1) distance 2. The 1st smallest distance is 0.

t1_02basic
Input{"nums":[1,1,2,6],"k":3}
Expected1

Pairs distances sorted: 0(1,1),1(1,2),4(6,2),5(6,1),5(6,1), etc. The 3rd smallest distance is 1.

t2_01edge
Input{"nums":[],"k":1}
Expected0

Empty array has no pairs; by definition return 0 as no distances exist.

t2_02edge
Input{"nums":[5],"k":1}
Expected0

Single element array has no pairs; distance is 0 by definition.

t2_03edge
Input{"nums":[2,2,2,2],"k":5}
Expected0

All elements identical; all pair distances are 0 regardless of k.

t2_04edge
Input{"nums":[1,1000000],"k":1}
Expected999999

Array with two elements has only one pair; distance is abs(1 - 1000000) = 999999.

t3_01corner
Input{"nums":[1,3,6,10,15],"k":7}
Expected9

Pairs sorted distances: 2,3,4,5,7,9,9,10,12,14; 7th smallest is 7. Tests off-by-one errors in counting pairs.

t3_02corner
Input{"nums":[1,1,1,1,1],"k":10}
Expected0

All pairs have distance 0; tests confusion between 0/1 knapsack style counting and pair counting.

t3_03corner
Input{"nums":[1,2,3,4,5],"k":4}
Expected1

Tests greedy trap: smallest distances are 1,1,1,2,... The 4th smallest is 2, not 1.

t4_01performance
Input{"nums":[0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370,380,390,400,410,420,430,440,450,460,470,480,490,500,510,520,530,540,550,560,570,580,590,600,610,620,630,640,650,660,670,680,690,700,710,720,730,740,750,760,770,780,790,800,810,820,830,840,850,860,870,880,890,900,910,920,930,940,950,960,970,980,990],"k":2500}
⏱ Performance - must finish in 2000ms

n=100, testing O(n log n + n log W) binary search approach within 2s time limit.

Practice

(1/5)
1. Given the following Python code implementing the optimal approach for Kth Largest in a Stream, what is the output of the last print statement?
import heapq

class KthLargest:
    def __init__(self, k: int, nums: list[int]):
        self.k = k
        self.heap = nums
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)

    def add(self, val: int) -> int:
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, val)
        elif val > self.heap[0]:
            heapq.heapreplace(self.heap, val)
        return self.heap[0]

kthLargest = KthLargest(3, [4, 5, 8, 2])
print(kthLargest.add(3))
print(kthLargest.add(5))
print(kthLargest.add(10))
print(kthLargest.add(9))
print(kthLargest.add(4))
easy
A. 8
B. 5
C. 4
D. 9

Solution

  1. Step 1: Trace heap initialization

    Initial nums = [4,5,8,2], heapified and trimmed to size k=3: heap becomes [4,5,8] after popping 2.
  2. Step 2: Trace add calls and heap updates

    add(3): 3 < 4 (heap[0]), no replace, return 4 add(5): 5 > 4, replace 4 with 5, heap now [5,5,8], return 5 add(10): 10 > 5, replace 5 with 10, heap now [5,10,8], return 5 add(9): 9 > 5, replace 5 with 9, heap now [8,10,9], return 8 add(4): 4 < 8, no replace, return 8
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Last add returns 8 as kth largest element [OK]
Hint: Heap root always holds kth largest element [OK]
Common Mistakes:
  • Off-by-one errors in heap size
  • Replacing when val <= heap[0]
  • Misunderstanding heap root meaning
2. What is the time complexity of the add(val) operation in the optimal min-heap approach for maintaining the kth largest element in a stream, assuming the heap size is k and the stream length is n?
medium
A. O(n ∙ log n) per add call, because the stream grows with n
B. O(1) per add call, as heap root access is constant time
C. O(k) per add call, because we may need to scan the heap to find the position
D. O(log k) per add call, since heap operations depend only on heap size k

Solution

  1. Step 1: Identify heap size and operations

    The heap size is fixed at k, independent of stream length n. Each add involves either a push or a replace operation on the heap.
  2. Step 2: Analyze complexity of heap operations

    Heap push or replace operations take O(log k) time because the heap has size k. Accessing the root is O(1), but add involves heapify steps.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Heap operations depend on k, not n, so O(log k) per add [OK]
Hint: Heap operations scale with heap size k, not stream length n [OK]
Common Mistakes:
  • Confusing n with k in complexity
  • Assuming linear scan of heap
  • Ignoring heapify cost
3. Suppose the frequency stack must support a new operation popK(k) that removes and returns the top k most frequent elements in order, breaking ties by recency. Which modification to the optimal heap-based approach correctly supports this operation efficiently?
hard
A. Perform k consecutive pop() calls on the heap, updating frequencies after each pop.
B. Use a separate max-heap for each frequency level and merge results on popK(k).
C. Modify the heap to store lists of elements per frequency and pop from these lists in order.
D. Maintain a global sorted list of elements by frequency and recency, and slice the top k on popK(k).

Solution

  1. Step 1: Understand popK(k) requirements

    We must pop the top k elements by frequency and recency order, updating frequencies after each pop.
  2. Step 2: Evaluate modifications

    Perform k consecutive pop() calls on the heap, updating frequencies after each pop. This performs k pops sequentially, each O(log n), correctly updating frequencies and maintaining heap invariants. Options A, B, and D either complicate the data structure or lose efficiency and correctness.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sequential pops maintain correctness and efficiency [OK]
Hint: Sequential pops maintain heap correctness for top-k [OK]
Common Mistakes:
  • Trying to pop multiple elements at once without updating frequencies
  • Using complex data structures that break heap invariants
4. Suppose the problem changes: you must find the k closest points to the origin, but points can be repeated multiple times (i.e., duplicates allowed and must be counted separately). Which modification to the Quickselect approach correctly handles this scenario without increasing time complexity significantly?
hard
A. Use a max heap of size k to keep track of closest points, allowing duplicates naturally.
B. Use a min heap to store all points and pop k times to get closest points, handling duplicates automatically.
C. Sort all points by distance and then remove duplicates before returning the first k points.
D. Modify Quickselect to partition points by distance and include duplicates in the partitioning logic without skipping any points.

Solution

  1. Step 1: Understand duplicates impact

    Duplicates must be treated as distinct points; Quickselect partitions by distance and does not rely on uniqueness.
  2. Step 2: Modify partition to handle duplicates correctly

    Partition logic remains the same; all points, including duplicates, are compared and placed correctly without skipping.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Quickselect handles duplicates naturally if partitioning is correct [OK]
Hint: Quickselect partitions all points regardless of duplicates [OK]
Common Mistakes:
  • Using min heap instead of max heap
  • Removing duplicates before selection
  • Sorting all points unnecessarily
5. Suppose you want to find the top k frequent words but now words can be reused infinitely many times (like unlimited supply). Which modification to the optimal bucket sort approach correctly handles this scenario?
hard
A. This problem reduces to a knapsack variant; bucket sort no longer applies
B. Modify frequency counting to consider infinite reuse, then apply bucket sort as usual
C. Use a dynamic programming approach to count combinations of words for frequencies
D. Use a max heap keyed by frequency and word lex order, repeatedly pop top k elements

Solution

  1. Step 1: Understand infinite reuse impact

    Infinite reuse means frequency counts are not fixed; problem becomes combinatorial.
  2. Step 2: Recognize problem class change

    Top k frequent words with unlimited reuse resembles knapsack or coin change, not simple frequency counting.
  3. Step 3: Bucket sort no longer applies

    Bucket sort relies on fixed frequencies; dynamic programming or other combinatorial methods are needed.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Infinite reuse breaks frequency counting assumptions [OK]
Hint: Infinite reuse changes problem class, bucket sort invalid [OK]
Common Mistakes:
  • Trying to reuse bucket sort with infinite counts
  • Ignoring combinatorial explosion
  • Assuming heap approach suffices
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