Closest latency pairs by minimum absolute difference
A monitoring service records latency readings (whole milliseconds) and wants to flag readings that are suspiciously close to one another.
Implement min_abs_diff_pairs(latencies: list[int]) -> list[list[int]].
- Let
dbe the smallest value of|a - b|over all pairs of readings taken from two different positions in the array. - Return every pair of values
[a, b]witha <= bandb - a == d. - Sort the result in ascending order by
a, then byb. - Readings can repeat. In that case
dis 0. List each repeated value once as[v, v], not once for each pair of positions. - Return
[]if there are fewer than two readings.
Constraints: 0 <= len(latencies) <= 10^5; -10^9 <= latencies[i] <= 10^9.
Example 1
Input: [40, 12, 31, 18, 33]
Output: [[31, 33]]
The smallest gap is 2, and only 31 and 33 are that close.
Example 2
Input: [9, 9, 3, 3, 3, 20]
Output: [[3, 3], [9, 9]]
Repeated readings make the smallest gap 0, so each repeated value is listed once.
Start with a simple approach, then improve it. Be ready to discuss repeated values and streaming input.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
