Find latency pairs with minimal difference
Company: Tesla
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array manipulation, pairwise comparison, and algorithmic efficiency by requiring identification of minimal absolute differences and construction of ordered latency pairs.
Constraints
- 0 <= len(latencies) <= 100000
- -1000000000 <= latencies[i] <= 1000000000
- All values in latencies are distinct
Examples
Input: ([4, 2, 1, 3],)
Expected Output: [[1, 2], [2, 3], [3, 4]]
Explanation: After sorting to [1, 2, 3, 4], every adjacent pair has difference 1, which is the minimum.
Input: ([1, 3, 6, 10, 15],)
Expected Output: [[1, 3]]
Explanation: The adjacent differences are 2, 3, 4, and 5, so the minimum is 2 from the pair [1, 3].
Input: ([8, 1, 5, 6, 13, 14],)
Expected Output: [[5, 6], [13, 14]]
Explanation: After sorting to [1, 5, 6, 8, 13, 14], the minimum adjacent difference is 1, achieved by [5, 6] and [13, 14].
Input: ([-7, -3, -1, 4],)
Expected Output: [[-3, -1]]
Explanation: Sorting gives [-7, -3, -1, 4]. The adjacent differences are 4, 2, and 5, so the minimum pair is [-3, -1].
Input: ([5],)
Expected Output: []
Explanation: There are fewer than 2 elements, so no valid pair exists.
Solution
def solution(latencies):
if len(latencies) < 2:
return []
arr = sorted(latencies)
min_diff = float('inf')
result = []
for i in range(1, len(arr)):
diff = arr[i] - arr[i - 1]
if diff < min_diff:
min_diff = diff
result = [[arr[i - 1], arr[i]]]
elif diff == min_diff:
result.append([arr[i - 1], arr[i]])
return resultTime complexity: O(n log n). Space complexity: O(n).
Hints
- Try sorting the array first. After sorting, the minimum absolute difference can only occur between neighboring elements.
- As you scan adjacent elements in sorted order, keep track of the smallest difference seen so far and rebuild the answer whenever you find a smaller one.