← Questions

Task delay times from the farthest smaller priority

0
AmazonCodingLast asked Sep 2025

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 - i or 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 of p[j..n-1]) only grows as j grows, so the rightmost j with suffix_min[j] < p[i] is found by binary search; that j holds 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

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