KatInterview

Wait Time Until a Strictly Larger Sensor Value

Stacks & QueuesAuto-graded · 21 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stackarraysnext-greater-element

Last updated

Find, for each position in a sequence, the distance to the next strictly larger element, using a monotonic stack to achieve linear time.

A sensor logs one integer value per day, and the values are stored in a list values, where values[i] is the reading on day i.

For every day i, determine how many days later the sensor first reports a value that is strictly larger than values[i]. In other words, find the smallest j > i with values[j] > values[i] and report j - i. If no such day exists, report 0 for that day.

Return a list of the same length as values, where entry i holds the answer for day i.

Rules

  • A later reading that is merely equal to the current one does not count; it must be strictly greater.
  • Only days after day i are considered.
  • The last day always has the answer 0.

Constraints

  • 1 <= len(values) <= 2 * 10^5
  • Each value fits in a 32-bit signed integer (it may be negative or zero).
  • The input should be solved efficiently enough for the maximum length; a quadratic scan is too slow.

Examples

Example 1

Input: wait_for_larger_value([30, 38, 30, 36, 35, 40, 28])

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

Hints

Hint 1

A brute-force scan to the right from each day is O(n^2) and fails on long non-increasing inputs. Look for a way to share work between days.

Hint 2

Sweep left to right and remember the days that are still waiting for a larger reading. When a new reading arrives, it may resolve several of those waiting days at once.

Hint 3

Keep a stack of indices (not values) whose readings are non-increasing from bottom to top. Pop while the top reading is strictly smaller than the current one, and record the index difference. Use strict comparison so equal values do not resolve each other.