KatInterview

K Nearest Value Pairs in a Sorted Sequence

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsortingtwo-pointers

Last updated

Tests whether a candidate can efficiently extract the k pairs with smallest gap from a sorted array using a heap-based k-way merge instead of brute force enumeration.

Problem

You are given a strictly increasing sequence of integers seq and a positive integer k. Your task is to find the k pairs of positions (i, j) with i < j whose values have the smallest gap, where gap is defined as seq[j] - seq[i].

Return those pairs as a list of two-element lists [seq[i], seq[j]], ordered from smallest gap to largest. When two pairs share the same gap, rank them by their left value ascending; if the left values also match, rank by their right value ascending.

Rules

  • Every valid pair consists of two elements drawn from different positions, with the left position strictly before the right position.
  • The gap of a pair is always non-negative because the sequence is strictly increasing.
  • The output list must contain exactly k pairs in the order described above.

Constraints

  • 2 <= len(seq) <= 10^5
  • -10^9 <= seq[i] <= 10^9
  • seq is strictly increasing: seq[i] < seq[i+1] for all valid i
  • 1 <= k <= min(10^5, len(seq) * (len(seq) - 1) // 2)

Examples

Example 1

Input: k_closest_pairs([1, 2, 5, 8], 3)

Output: [[1, 2], [2, 5], [5, 8]]

Example 2

Input: k_closest_pairs([1, 3, 4, 7, 10], 2)

Output: [[3, 4], [1, 3]]

Hints

Hint 1

The sequence is sorted, so for any fixed left index i the gaps to the right grow monotonically. That means all pairs starting at i form a sorted sub-list on their own — can you exploit that structure?

Hint 2

Think of each left index as the head of its own sorted list of candidates. Merging k sorted lists efficiently is a classic heap problem: seed the heap with the smallest candidate from every list, then advance one list at a time.

Hint 3

The heap entry needs to encode more than just the gap. To get the tie-break right automatically, store (gap, left_value, right_value, left_index, right_index) so Python's default tuple comparison does the sorting work for you.