Task delay times from the farthest smaller priority
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests monotonic stack, binary-search and arrays.
Tasks have priorities given in an array and run from right to left. A task's delay time is j - i, where j is the rightmost index after i whose priority is strictly smaller than priorities[i]; if there is none, the delay time is 0. Return the delay time of every task. The O(n²) scan is too slow for the input sizes.
Interface
Unless you agree on a different interface with the interviewer, assume:
delay_times(priorities: list[int]) -> list[int]
Example
delay_times([8, 2, 11, 4, 9, 4, 7]) -> [6, 0, 4, 0, 2, 0, 0]
# 8: the rightmost smaller value is the 7 at index 6, so 6 - 0 = 6
# 11 -> 7 at index 6 (4); 9 -> 7 at index 6 (2); 2, 4, 4 and 7 have nothing smaller after them
delay_times([3, 1, 3, 2]) -> [3, 0, 1, 0]
delay_times([5, 5, 5]) -> [0, 0, 0] # equal is not smaller
delay_times([]) -> []
Constraints
-
0 <= n <= 2 · 10^5;-10^9 <= priorities[i] <= 10^9; values may repeat.
Clarifying questions
- The rightmost smaller element, or the nearest one? (The rightmost.)
- Does an equal priority count as smaller? (No.)
- Should the delay be
j - ior the number of tasks in between?
What a strong answer covers
- Recognising that "rightmost smaller" is not the usual "next smaller" monotonic-stack problem.
- A suffix minimum array:
suffix_min[j](the minimum ofp[j..n-1]) only grows asjgrows, so the rightmostjwithsuffix_min[j] < p[i]is found by binary search; thatjholds the smaller value. O(n log n) time, O(n) space. - Alternatively, process right to left with a segment tree or Fenwick tree over compressed values that stores the largest index seen per value, and query the maximum index among values below
p[i]. - Duplicates and strictness handled in the comparison; the empty array.
- A brute-force checker on random small inputs.
Follow-ups
- Return the nearest smaller element to the right instead. (A monotonic stack, O(n).)
- Priorities change one at a time and the delays must be answered after each change.
Where it's asked
- Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
monotonic stack · binary-search · arrays
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
