K Nearest Value Pairs in a Sorted Sequence
Heaps, Sorting & SearchAuto-graded · 24 test casesLast 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
kpairs in the order described above.
Constraints
2 <= len(seq) <= 10^5-10^9 <= seq[i] <= 10^9seqis strictly increasing:seq[i] < seq[i+1]for all validi1 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why brute force doesn't scale
A sequence of length n = 10^5 has roughly 5 × 10^9 possible pairs. Generating every pair, computing its gap, and sorting the full list is far too slow in both time and memory. The key is to produce pairs in sorted order lazily and stop as soon as we have k of them.
Sorted rows and k-way merge
Because seq is strictly increasing, if you fix a left index i and slide the right index j from i+1 to n-1, the gaps grow strictly:
seq[i+1] - seq[i] < seq[i+2] - seq[i] < ... < seq[n-1] - seq[i]
So every left index i heads a sorted virtual list of candidate pairs. There are n-1 such lists. The problem reduces to pulling the k smallest elements from n-1 sorted lists — exactly the k-way merge pattern solved by a min-heap:
- Seed the heap with the first (smallest-gap) pair from every row:
(i, i+1)for eachi. - Pop the globally smallest candidate, add it to the result.
- Push that row's next candidate
(i, j+1)ifj+1 < n. - Repeat
ktimes.
Encoding the tie-break in the heap key
Each heap entry is a 5-tuple (gap, left_val, right_val, left_idx, right_idx). Python compares tuples left-to-right, so the heap naturally orders by:
- gap ascending, then
- left value ascending, then
- right value ascending.
That is exactly the required output order. The index fields left_idx and right_idx are only carried so we know which row to advance; they never affect the required ordering because (left_val, right_val) uniquely identifies a pair in a strictly increasing sequence.
Correctness argument
Invariant: for every row that still has unreturned pairs, the heap holds exactly that row's smallest unreturned pair.
- This holds initially: every row's head is in the heap.
- When we pop row
i's current head(i, j), we immediately push its successor(i, j+1)(when it exists), restoring the invariant for rowi. - The global minimum pair belongs to some row; by the invariant it is in the heap, so the heap's minimum is the global minimum.
Because each (i, j) enters the heap at most once (only via its predecessor or as a row head), no pair is returned twice.
Edge cases
len(seq) == 2: the heap starts with a single entry. After one pop nothing is pushed, and the loop ends naturally.k == n*(n-1)//2: every pair is eventually popped. Thenj < nguard ensures we never push out-of-bounds indices, so the heap empties cleanly.- Negative values or large magnitudes: gaps can reach about
2 × 10^9. Python integers handle this without overflow.
Complexity
- Time:
O(n + k log n)—heapifyisO(n); each of thekiterations does one pop and at most one push on a heap of size at mostn-1, costingO(log n)each. - Space:
O(n)for the heap,O(k)for the output.
Reference solution
from typing import List
import heapq
def k_closest_pairs(seq: List[int], k: int) -> List[List[int]]:
n = len(seq)
# Seed the heap with the closest (adjacent) pair from each left index i.
# Heap key: (gap, left_value, right_value, left_index, right_index)
# Python tuple comparison handles all tie-breaking automatically.
heap = []
for i in range(n - 1):
j = i + 1
heap.append((seq[j] - seq[i], seq[i], seq[j], i, j))
heapq.heapify(heap)
result = []
for _ in range(k):
_gap, a, b, i, j = heapq.heappop(heap)
result.append([a, b])
# Advance row i to the next right index, if one exists.
nj = j + 1
if nj < n:
heapq.heappush(heap, (seq[nj] - seq[i], seq[i], seq[nj], i, nj))
return result