KatInterview

Closest Response Times: List the Tightest Increasing Pairs

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingsortingarraysadjacent-difference

Last updated

Find the smallest absolute gap between any two readings, then list every strictly increasing pair achieving it, handling duplicates correctly. Tests sorting and adjacent-gap reasoning.

Closest Response Times

You are given a list of integer response-time readings (in milliseconds) collected from a service. Values may be negative, and the same value may appear more than once.

Let d be the smallest absolute difference between any two elements of the list, where two elements at different positions are always allowed to be compared, even if they hold equal values.

Return every pair [a, b] that satisfies both of the following:

  • a < b (strictly increasing), and
  • b - a == d.

Output rules

  • Return the pairs as a list of two-element lists.
  • Sort the pairs by a ascending, then by b ascending.
  • If the list has fewer than two elements, return an empty list.
  • If any value is repeated, then d is 0. No strictly increasing pair can have a difference of 0, so the answer is an empty list. A pair with a larger difference does not qualify just because it is the closest distinct pair.

Constraints

  • 0 <= len(readings) <= 10^5
  • Each reading is an integer that fits in a 64-bit signed integer.
  • The input list should not be relied upon to be sorted.
  • Aim for better than quadratic time.

Examples

Example 1

Input: closest_reading_pairs([4, 2, 1, 3])

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

Example 2

Input: closest_reading_pairs([1, 3, 6, 10, 15])

Output: [[1, 3]]

Example 3

Input: closest_reading_pairs([1, 1, 3])

Output: []

Hints

Hint 1

Think about which elements could possibly be the closest to a given value. What happens to the answer if you first put the readings in order?

Hint 2

After sorting, the smallest difference over all pairs is always found between two neighbors. A pair that skips an element spans at least two gaps.

Hint 3

If the smallest gap is 0 there is a duplicate, and no strictly increasing pair can match it, so return an empty list. Otherwise, collect every neighboring pair whose gap equals the minimum.