Kth Smallest Weight Gap Among All Pairs of Packages
Last updated: November 29, 2026
Quick Overview
Given package weights, consider the absolute weight difference of every unordered pair of distinct packages. Return the kth smallest of these differences.
Amazon
November 29, 20260
0
0 solved
Given package weights, consider the absolute weight difference of every unordered pair of distinct packages. Return the kth smallest of these differences.
A Hard Amazon onsite problem combining sorting, binary search on the answer and a two-pointer count. It fits balancing loads on a conveyor where near-equal packages are paired; interviewers check that you avoid generating all n^2 pairs.
What the Interviewer Expects
- Sort the weights first
- Binary search on the gap value d in [0, max - min]
- Count pairs with difference <= d in O(n) with two pointers
- Return the smallest d with count >= k
- Analyze O(n log n + n log W)
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you find the kth largest gap instead?
- What if weights arrived as a stream and k was fixed?
- Can a heap solution work, and what would it cost?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Inputs: list of n >= 2 integers and k with 1 <= k <= n(n-1)/2. Output: the kth smallest |w[i] - w[j]| over pairs i < j....
High-Level Design
After sorting, for a fixed right index j the pairs with difference <= d are those with left index in [i, j - 1], where i is the first index with w[j] - w[i] <= d. As j increases, i never moves left, s...