Pick the fix
Why is the monotonic stack solution O(n) even though it has a while loop inside a for loop?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Each day is pushed once and popped at most once
Right: total pops across the whole run cannot exceed n.
Counting pushes and pops over the whole run gives at most 2n stack operations.
Why not the others?
- B The while loop always runs once. It can pop many days in one step; the bound comes from the total.
- C The stack never holds more than two days. It can hold a long run of falling temperatures.
Steps come from running the Python solution.
Text version
Week one:
- Push 0; waiting [30]. Day 0 (30): nothing to answer
- Push 1, answer 0; waiting [32]. Day 1 (32) answers day 0
- Push 2; waiting [32, 31]. Day 2 (31): nothing to answer
- Push 3; waiting [32, 31, 29]. Day 3 (29): nothing to answer
- Push 4, answer 3, 2, 1; waiting [33]. Day 4 (33) answers days 3, 2, 1
- Push 5; waiting [33, 28]. Day 5 (28): nothing to answer
- Push 6, answer 5, 4; waiting [35]. Day 6 (35) answers days 5, 4
Result: [1, 3, 2, 1, 2, 1, 0]
Week two:
- Push 0; waiting [40]. Day 0 (40): nothing to answer
- Push 1; waiting [40, 38]. Day 1 (38): nothing to answer
- Push 2; waiting [40, 38, 36]. Day 2 (36): nothing to answer
- Push 3, answer 2, 1, 0; waiting [41]. Day 3 (41) answers days 2, 1, 0
- Push 4; waiting [41, 39]. Day 4 (39): nothing to answer
- Push 5, answer 4, 3; waiting [42]. Day 5 (42) answers days 4, 3
Result: [3, 2, 1, 2, 1, 0]