← Questions

Closest latency pairs by minimum absolute difference

0
TeslaMicrosoftCodingLast asked Feb 2026

A coding interview question asked in Microsoft's technical phone screen and at Tesla, last asked Feb 2026. It tests arrays and sorting.

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 d be 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] with a <= b and b - a == d.
  • Sort the result in ascending order by a, then by b.
  • Readings can repeat. In that case d is 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.

Clarifying questions

  • With repeats, is d always 0, and are only the repeated values listed?
  • Should pairs be values, not positions? (Yes.)
  • Can the difference overflow 32 bits? (Yes, up to 2 * 10^9.)
  • Is the input small enough to sort in memory?

What a strong answer covers

  • Sorts the readings. The closest pair is always two neighbours in sorted order.
  • Finds the smallest neighbour gap, then collects every neighbour pair with that gap. When the gap is 0, it lists each repeated value once.
  • That is O(n log n) time and O(n) memory, and the output comes out sorted.
  • Starts from the O(n^2) pairwise check, then explains why sorting is enough.
  • Tests both examples, fewer than two readings, all equal readings, negative values, and several pairs with the same gap.

Follow-ups

  • Readings stream in: keep a sorted structure and the current smallest gap.
  • Return all pairs within a threshold t, not only the closest.
  • The k closest pairs.
  • Report positions instead of values.

Where it's asked

What it tests

arrays · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding