Compute rightmost-smaller delay times
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates proficiency in efficient array-processing algorithms, reasoning about time and space complexity, and correct handling of duplicates and edge cases when computing distances to rightmost smaller elements.
Constraints
- 0 <= n <= 10^5
- -10^9 <= priorities[i] <= 10^9
- The array may contain duplicate values; equal values are NOT counted as smaller.
- Must run in better than O(n^2) time.
Examples
Input: ([8, 2, 11, 4, 9, 4, 7],)
Expected Output: [6, 0, 4, 0, 2, 0, 0]
Explanation: The worked example: 8->7@6 (6), 11->7@6 (4), 9->7@6 (2); 2 and the 4's and final 7 have no strictly-smaller element to the right.
Input: ([],)
Expected Output: []
Explanation: Empty array returns an empty result.
Hints
- A naive scan-right per element is O(n^2). You need a structure that answers 'rightmost position with a value below a threshold' quickly.
- Build a segment tree over positions storing the minimum value in each segment.
- To find the rightmost qualifying index, descend the tree preferring the right child first; only enter a subtree whose stored minimum is < the query value. This yields the rightmost match in O(log n).
- Duplicates are handled by the strict '<' comparison: equal values never qualify. Strictly increasing arrays yield all zeros; strictly decreasing arrays yield delay[i] = n-1-i.