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 to42on day1before rising to49on day2(2 - 0 = 2days). - Day
1(42) is exceeded on the very next day by49(2 - 1 = 1day). - Day
2(49) waits across days3and4until52arrives on day5(5 - 2 = 3days). - Day
3(44) sees an equal44on day4(not strictly higher) and is exceeded by52on day5(5 - 3 = 2days). - Day
4(44) is exceeded on day5by52(5 - 4 = 1day). - Days
5(52) and6(39) have no larger value after them, so both evaluate to0.
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
8at index2only ties index1), every position returns0.
Constraints
1 <= len(readings) <= 2 * 10^5-2^31 <= readings[i] <= 2^31 - 1
Step-by-step walkthrough
Understand the problem and output rules
We receive an integer list
readingsof lengthn(1 <= n <= 2 * 10^5), wherereadings[i]is the measurement on dayi. For every dayi, we must compute the distancej - ito the earliest future dayj > iwith a strictly higher measurement (readings[j] > readings[i]), or0when no future day beatsreadings[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 another44on day4, so day4does not answer day3.Why scanning forward from each day is too slow
The brute-force idea checks each day
iby walkingj = i + 1, i + 2, ...untilreadings[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 answerWhat goes wrong when
readingsis strictly decreasing, like[200000, 199999, ..., 1]? Every single dayiscans all the way to the end of the list without finding a larger value! That performsn * (n - 1) // 2comparisons — roughly2 * 10^10checks forn = 2 * 10^5, which times out by orders of magnitude.Notice why it wastes work: when day
2(49) stays unresolved across days3(44) and4(44), a naive loop re-scans those dip days instead of letting day5(52) resolve all waiting days in one sweep.Key idea: keep a monotonic stack of unresolved days
Sweep
todayfrom0ton - 1and maintain a stackwaiting_dayscontaining the indices of days that have not yet seen a strictly higher reading.Think about what the measurements inside
waiting_daysmust 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 whentoday_reading = readings[today]arrives:- Inspect the top of the stack (
waiting_days[-1]), which holds the smallest value among all unresolved days. - While
readings[waiting_days[-1]] < today_reading, popearlier_day = waiting_days.pop()and recordanswer[earlier_day] = today - earlier_day. - 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, sotoday_readingcannot beat any of them! - Push
todayontowaiting_daysbecausetodayitself is now waiting for a future higher reading.
Notice we push day indices (
today), not raw values: from an indexidxwe can look up both the wait distancetoday - idxand the valuereadings[idx].- Inspect the top of the stack (
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): Isreadings[0] < 3?3 < 3isFalse! So day0stays on the stack, and day1is pushed on top:waiting_days = [0, 1](values3 >= 3). - Day
2(4):readings[1] < 4-> pops1(answer[1] = 2 - 1 = 1); nextreadings[0] < 4-> pops0(answer[0] = 2 - 0 = 2). - Result:
[2, 1, 0]. Had we written<=, day1(3) would have falsely resolved day0(3)!
- Day
- Days that never see a higher reading: Initializing
answer = [0] * num_daysupfront means any index still sitting inwaiting_dayswhen the loop finishes already holds0inanswer— no cleanup loop required!
- Duplicate readings (
Trace Example 1 step by step
Let's trace
readings = [45, 42, 49, 44, 44, 52, 39], writing each stack entry asday(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
5popped three items at once, each of the7indices was pushed once and popped at most once!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 awhileloop sits inside aforloop, each day index0 .. n - 1is pushed ontowaiting_daysexactly once and popped at most once across the entire run. By amortized analysis — summing the total operations over the whole sequence rather than multiplyingniterations by a raren-pop spike — theforloop runsnsteps and allwhileiterations combined execute at mostnpops, totalingO(n)work. - Space:
O(n). The output listanswerholdsnintegers, andwaiting_daysholds at mostnindices (reaching sizenwhenreadingsnever increases, such as[12, 8, 8, -3]in Example 2).
Edge cases
- Single day (
[42]): Pushed ontowaiting_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 at0([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 wait1, returning[1, 1, 1, 1, 0]. - Negative values and 32-bit signed extremes (
-2^31to2^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 (
[], outside1 <= n): Returns[]cleanly without extra guards.
Common mistakes
- Using
<=instead of<in thewhilecondition: Popping onreadings[waiting_days[-1]] <= today_readingtreats 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 store44on the stack, you no longer know which day44came from when computingtoday - earlier_day(or which slot ofanswerto write!). Storing indices gives you bothearlier_dayandreadings[earlier_day]. - Initializing
answerwith-1instead of0: The specification requires0(not-1) when no future day has a higher reading; initializing[0] * num_dayshandles unresolved stack leftovers automatically. - Mistaking nested
for+whileforO(n^2)time: In an interview, always state explicitly why the total number ofpop()calls across the entire loop cannot exceed thenappend()calls.
Alternative approaches
- Right-to-left monotonic stack (
O(n)time,O(n)space): Sweepifromn - 1down to0, maintaining a stack of future candidate indices. Popstack[-1]whilereadings[stack[-1]] <= readings[i](here<=is right, because an earlier equal/larger day hides an equal/smaller later day!), thenanswer[i] = stack[-1] - iifstackis non-empty else0, and pushi. - Right-to-left jump pointers (
O(n)time,O(1)auxiliary space beyondanswer): Sweepifromn - 2down to0. Startj = i + 1; whilereadings[j] <= readings[i]andanswer[j] > 0, jump directly toj += answer[j](skipping over values already known to be<= readings[j] <= readings[i]). Ifreadings[j] > readings[i], setanswer[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 ofwaiting_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 - 1back to index0? Loopstepfrom0to2 * n - 1usingidx = step % n. Pop wheneverreadings[waiting_days[-1]] < readings[idx]and setanswer[earlier_day] = step - earlier_day, while only pushingstepduring the first pass (if step < n:). Running two passes inO(n)time lets every element inspect alln - 1subsequent elements in wraparound order. - How would you find the farthest future day
j > iwithreadings[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 indicesiin a left-to-right pass, then sweepjfromn - 1down to0popping anyiwithreadings[i] < readings[j]to maximizej - iinO(n)total time.
Follow-up questions
- How would your design work if measurements arrived one per day over a live stream instead of an in-memory array?
- How would you adapt the algorithm if the sequence wrapped around circularly from index `n - 1` back to index `0`?
- How would you find the farthest future day `j > i` with `readings[j] > readings[i]` rather than the nearest one?
Similar questions
- Grounded RAG Assistant for Automotive Documentation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One