Days Until Next Higher Measurement

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an integer list readings of length n, where readings[i] records the measurement observed on day i (0-indexed), implement days_until_higher_reading(readings: List[int]) -> List[int].

For every day i (0 <= i < n), determine the minimum positive wait j - i to reach a future day j > i whose measurement is strictly greater than day i's measurement (readings[j] > readings[i]). If no subsequent day has a strictly larger value, record 0 at index i. Ties (readings[j] == readings[i]) do not count as higher measurements.

Examples

Example 1

Input:  readings = [45, 42, 49, 44, 44, 52, 39]
Output: [2, 1, 3, 2, 1, 0, 0]
  • Day 0 (45) dips to 42 on day 1 before rising to 49 on day 2 (2 - 0 = 2 days).
  • Day 1 (42) is exceeded on the very next day by 49 (2 - 1 = 1 day).
  • Day 2 (49) waits across days 3 and 4 until 52 arrives on day 5 (5 - 2 = 3 days).
  • Day 3 (44) sees an equal 44 on day 4 (not strictly higher) and is exceeded by 52 on day 5 (5 - 3 = 2 days).
  • Day 4 (44) is exceeded on day 5 by 52 (5 - 4 = 1 day).
  • Days 5 (52) and 6 (39) have no larger value after them, so both evaluate to 0.

Example 2

Input:  readings = [12, 8, 8, -3]
Output: [0, 0, 0, 0]
  • Because no later day ever strictly exceeds an earlier day (the repeated 8 at index 2 only ties index 1), every position returns 0.

Constraints

  • 1 <= len(readings) <= 2 * 10^5
  • -2^31 <= readings[i] <= 2^31 - 1

Step-by-step walkthrough

  1. Understand the problem and output rules

    We receive an integer list readings of length n (1 <= n <= 2 * 10^5), where readings[i] is the measurement on day i. For every day i, we must compute the distance j - i to the earliest future day j > i with a strictly higher measurement (readings[j] > readings[i]), or 0 when no future day beats readings[i].

    index:     0    1    2    3    4    5    6
    readings: 45   42   49   44   44   52   39
               │    │    │    │    │    │    └─► no future day -> 0
               │    │    │    │    │    └──────► max value, never beaten -> 0
               │    │    │    │    └───────────► beaten at index 5 (52 > 44): 5 - 4 = 1
               │    │    │    └────────────────► index 4 ties (44 == 44); beaten at index 5: 5 - 3 = 2
               │    │    └─────────────────────► beaten at index 5 (52 > 49): 5 - 2 = 3
               │    └──────────────────────────► beaten at index 2 (49 > 42): 2 - 1 = 1
               └───────────────────────────────► beaten at index 2 (49 > 45): 2 - 0 = 2
    
    output:  [ 2,   1,   3,   2,   1,   0,   0 ]
    

    Pay close attention to strictly: in Example 1, day 3 (44) is followed by another 44 on day 4, so day 4 does not answer day 3.

  2. Why scanning forward from each day is too slow

    The brute-force idea checks each day i by walking j = i + 1, i + 2, ... until readings[j] > readings[i]:

    def brute_days(readings: List[int]) -> List[int]:
        n = len(readings)
        answer = [0] * n
        for i in range(n):
            for j in range(i + 1, n):
                if readings[j] > readings[i]:
                    answer[i] = j - i
                    break
        return answer
    

    What goes wrong when readings is strictly decreasing, like [200000, 199999, ..., 1]? Every single day i scans all the way to the end of the list without finding a larger value! That performs n * (n - 1) // 2 comparisons — roughly 2 * 10^10 checks for n = 2 * 10^5, which times out by orders of magnitude.

    Notice why it wastes work: when day 2 (49) stays unresolved across days 3 (44) and 4 (44), a naive loop re-scans those dip days instead of letting day 5 (52) resolve all waiting days in one sweep.

  3. Key idea: keep a monotonic stack of unresolved days

    Sweep today from 0 to n - 1 and maintain a stack waiting_days containing the indices of days that have not yet seen a strictly higher reading.

    Think about what the measurements inside waiting_days must look like from bottom (oldest) to top (newest): they can never increase! Why? Because if a higher day had arrived after a lower waiting day, that higher day would already have resolved and popped the lower day!

    Stack of waiting days (bottom -> top) is always non-increasing in value:
    
      bottom [ day 2 (49),  day 3 (44),  day 4 (44) ] top     <-- 49 >= 44 >= 44
                                                  ▲
                         smallest waiting value sits right on TOP!
    

    That single invariant gives us an O(1) way to find who gets resolved when today_reading = readings[today] arrives:

    1. Inspect the top of the stack (waiting_days[-1]), which holds the smallest value among all unresolved days.
    2. While readings[waiting_days[-1]] < today_reading, pop earlier_day = waiting_days.pop() and record answer[earlier_day] = today - earlier_day.
    3. As soon as the stack empties or readings[waiting_days[-1]] >= today_reading, stop immediately — every day deeper in the stack has an even larger (or equal) value, so today_reading cannot beat any of them!
    4. Push today onto waiting_days because today itself is now waiting for a future higher reading.

    Notice we push day indices (today), not raw values: from an index idx we can look up both the wait distance today - idx and the value readings[idx].

  4. Why strict `<` handles duplicate readings and why `[0] * n` handles the end

    Let's verify the two trickiest boundary rules:

    • Duplicate readings ([3, 3, 4]):
      • Day 0 (3): waiting_days = [0].
      • Day 1 (3): Is readings[0] < 3? 3 < 3 is False! So day 0 stays on the stack, and day 1 is pushed on top: waiting_days = [0, 1] (values 3 >= 3).
      • Day 2 (4): readings[1] < 4 -> pops 1 (answer[1] = 2 - 1 = 1); next readings[0] < 4 -> pops 0 (answer[0] = 2 - 0 = 2).
      • Result: [2, 1, 0]. Had we written <=, day 1 (3) would have falsely resolved day 0 (3)!
    • Days that never see a higher reading: Initializing answer = [0] * num_days upfront means any index still sitting in waiting_days when the loop finishes already holds 0 in answer — no cleanup loop required!
  5. Trace Example 1 step by step

    Let's trace readings = [45, 42, 49, 44, 44, 52, 39], writing each stack entry as day(reading):

    today  reading  while top < reading (pops & answers)                   waiting_days after push
    -----  -------  -----------------------------------------------------  ------------------------------
      0      45     stack empty                                            [ 0(45) ]
      1      42     45 < 42 is False                                       [ 0(45), 1(42) ]
      2      49     pop 1(42): answer[1] = 2 - 1 = 1                       [ 2(49) ]
                    pop 0(45): answer[0] = 2 - 0 = 2
      3      44     49 < 44 is False                                       [ 2(49), 3(44) ]
      4      44     44 < 44 is False (tie stays waiting!)                  [ 2(49), 3(44), 4(44) ]
      5      52     pop 4(44): answer[4] = 5 - 4 = 1                       [ 5(52) ]
                    pop 3(44): answer[3] = 5 - 3 = 2
                    pop 2(49): answer[2] = 5 - 2 = 3
      6      39     52 < 39 is False                                       [ 5(52), 6(39) ]
    
    Left on stack: 5(52) and 6(39) -> keep default 0.
    Final answer:  [2, 1, 3, 2, 1, 0, 0]
    

    Even though day 5 popped three items at once, each of the 7 indices was pushed once and popped at most once!

  6. Complete solution

    Here is the complete O(n) solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def days_until_higher_reading(readings: List[int]) -> List[int]:
        num_days = len(readings)
        # answer[i]: days to wait after day i for a strictly higher reading (0 if none exists)
        answer = [0] * num_days
        # waiting_days: monotonic stack of day indices [i_0, i_1, ...] still awaiting a higher reading.
        # Invariant: readings[waiting_days[0]] >= readings[waiting_days[1]] >= ... >= readings[waiting_days[-1]].
        waiting_days: List[int] = []
    
        # Sweep left-to-right so each today_reading immediately resolves smaller waiting days.
        for today in range(num_days):
            today_reading = readings[today]
    
            # Use strict '<' (not '<=') because an equal reading does NOT count as higher.
            # Once the top waiting day has reading >= today_reading, every deeper day on the stack
            # is also >= today_reading, so we can stop popping right away.
            while waiting_days and readings[waiting_days[-1]] < today_reading:
                earlier_day = waiting_days.pop()
                answer[earlier_day] = today - earlier_day
    
            # Today now waits for a future day strictly higher than today_reading.
            waiting_days.append(today)
    
        # Any day index still left in waiting_days never saw a higher reading and keeps 0.
        return answer
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine people arriving one per day and standing in a line facing the entrance, each waiting to spot the very first newcomer who is strictly taller than they are. Whenever a newcomer walks in, anyone shorter standing at the back of the waiting line immediately gets their answer and leaves the line! Because shorter people at the back always leave as soon as a taller person arrives, the people still waiting in line are automatically ordered from tallest at the front to shortest at the back. In computer science, a stack is a last-in, first-out list where we only add (append) and remove (pop) from the top end in O(1) time, and this self-sorting pattern is called a monotonic stack — a stack whose stored items stay in non-increasing (or non-decreasing) order because any out-of-order tops are popped before pushing the new item.

Why does the obvious nested loop fail? Scanning forward from every day i (for j in range(i + 1, n)) repeats work over the exact same valleys: on a decreasing sequence like [99, 98, 97, ...], every day walks all the way to the end of the array, causing O(n^2) comparisons (~2 * 10^10 checks at n = 200,000). Keeping unresolved day indices on a monotonic stack lets one high measurement resolve all smaller waiting days in bulk without ever checking a resolved day again.

Let's trace the middle slice [49, 44, 44, 52] from Example 1:

Start: answer = [0, 0, 0, 0], waiting_days = []

- Day 0 (49): stack empty -> push 0.                          waiting_days = [0(49)]
- Day 1 (44): top 49 < 44 is False -> push 1.                 waiting_days = [0(49), 1(44)]
- Day 2 (44): top 44 < 44 is False (tie waits!) -> push 2.    waiting_days = [0(49), 1(44), 2(44)]
- Day 3 (52): pops 2 (ans[2]=3-2=1), pops 1 (ans[1]=3-1=2),
              pops 0 (ans[0]=3-0=3); push 3.                  waiting_days = [3(52)]
End: Day 3 stays on stack with default 0 -> returns [3, 2, 1, 0].

Complexity

Let n be the number of days (len(readings)).

  • Time: O(n). Although a while loop sits inside a for loop, each day index 0 .. n - 1 is pushed onto waiting_days exactly once and popped at most once across the entire run. By amortized analysis — summing the total operations over the whole sequence rather than multiplying n iterations by a rare n-pop spike — the for loop runs n steps and all while iterations combined execute at most n pops, totaling O(n) work.
  • Space: O(n). The output list answer holds n integers, and waiting_days holds at most n indices (reaching size n when readings never increases, such as [12, 8, 8, -3] in Example 2).

Edge cases

  • Single day ([42]): Pushed onto waiting_days, never popped, returns [0].
  • All equal readings ([5, 5, 5]): Because we check strict <, none of the equal readings pop earlier copies, leaving every entry at 0 ([0, 0, 0]).
  • Non-increasing with negatives ([12, 8, 8, -3]): Every day stays on the stack until the end, returning [0, 0, 0, 0].
  • Strictly increasing ([1, 2, 3, 4, 5]): Each day immediately pops the previous day with wait 1, returning [1, 1, 1, 1, 0].
  • Negative values and 32-bit signed extremes (-2^31 to 2^31 - 1): Only < comparisons between readings and subtraction on indices (0 .. n - 1) are performed, so negative values and extreme bounds never overflow or misbehave.
  • Empty list ([], outside 1 <= n): Returns [] cleanly without extra guards.

Common mistakes

  • Using <= instead of < in the while condition: Popping on readings[waiting_days[-1]] <= today_reading treats equal future measurements as "higher," turning [49, 44, 44, 52] into [3, 1, 1, 0] instead of [3, 2, 1, 0].
  • Pushing values (readings[today]) instead of day indices (today): If you only store 44 on the stack, you no longer know which day 44 came from when computing today - earlier_day (or which slot of answer to write!). Storing indices gives you both earlier_day and readings[earlier_day].
  • Initializing answer with -1 instead of 0: The specification requires 0 (not -1) when no future day has a higher reading; initializing [0] * num_days handles unresolved stack leftovers automatically.
  • Mistaking nested for + while for O(n^2) time: In an interview, always state explicitly why the total number of pop() calls across the entire loop cannot exceed the n append() calls.

Alternative approaches

  • Right-to-left monotonic stack (O(n) time, O(n) space): Sweep i from n - 1 down to 0, maintaining a stack of future candidate indices. Pop stack[-1] while readings[stack[-1]] <= readings[i] (here <= is right, because an earlier equal/larger day hides an equal/smaller later day!), then answer[i] = stack[-1] - i if stack is non-empty else 0, and push i.
  • Right-to-left jump pointers (O(n) time, O(1) auxiliary space beyond answer): Sweep i from n - 2 down to 0. Start j = i + 1; while readings[j] <= readings[i] and answer[j] > 0, jump directly to j += answer[j] (skipping over values already known to be <= readings[j] <= readings[i]). If readings[j] > readings[i], set answer[i] = j - i. This eliminates the stack array altogether, though the left-to-right stack is much easier to write bug-free and also works on live streams.

Follow-up questions

  • How would your design work if measurements arrived one per day over a live stream instead of an in-memory array? Our left-to-right monotonic stack already works online (processing one measurement at a time without needing future inputs first)! Each day today, (today, today_reading) is compared against the top of waiting_days, immediately emitting (earlier_day, today - earlier_day) for every resolved day; memory at any moment is proportional only to the number of currently unresolved days.
  • How would you adapt the algorithm if the sequence wrapped around circularly from index n - 1 back to index 0? Loop step from 0 to 2 * n - 1 using idx = step % n. Pop whenever readings[waiting_days[-1]] < readings[idx] and set answer[earlier_day] = step - earlier_day, while only pushing step during the first pass (if step < n:). Running two passes in O(n) time lets every element inspect all n - 1 subsequent elements in wraparound order.
  • How would you find the farthest future day j > i with readings[j] > readings[i] rather than the nearest one? That turns the problem from Next Greater Element into Maximum Width Ramp: build a strictly decreasing stack of candidate start indices i in a left-to-right pass, then sweep j from n - 1 down to 0 popping any i with readings[i] < readings[j] to maximize j - i in O(n) total time.

Follow-up questions

Similar questions

More Sonatus interview questions

All 2 Sonatus questions →