Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-456monotonic-stack · stacks
A live channel logs its viewer count every hour. An analyst looks for a soft landing: a count, then a later spike, then a still later count that is above the first one but below the spike.
In other words, the viewers rose to a peak and fell back, but not all the way back. The log can hold 100,000 hours, so trying every triple of hours is too slow.
Write has_soft_landing(counts).
counts[h] is the number of viewers in hour h.true if there are three hours i < j < k with counts[i] < counts[k] < counts[j], and false otherwise.Input: counts = [5, 9, 7, 3, 8, 6]
Output: trueThe scan reads the hours from the last to the first. The stack holds counts that could still be a landing. The landing is the largest count that a later, higher count has covered, or -1 if there is none.
| Hour read | Count | Check | stack after |
landing after |
|---|---|---|---|---|
| 5 | 6 | no landing yet | 6 | -1 |
| 4 | 8 | no landing yet; 8 is above 6, so 6 is covered | 8 | 6 |
| 3 | 3 | 3 is below the landing 6: found | stop | stop |
Hours count from 0. The pattern is 3, 8, 6: hour 3 has count 3, hour 4 has the spike 8, and hour 5 has the count 6. Since 3 is below 6 and 6 is below 8, it is a soft landing.
Input: counts = [9, 7, 5, 3]
Output: falseThe counts only fall. A spike needs a lower count before it, and none of these has one.
Input: counts = [3, 5, 0, 4]
Output: trueThe count 3, the spike 5 and the count 4 form the pattern. The 0 between them does not matter.
1 ≤ len(counts) ≤ 100,0000 ≤ counts[h] ≤ 10^6Trying every triple of hours costs about n^3 / 6 steps. For 100,000 hours that is 1.7 × 10^14, far beyond a single second.
Even a loop over pairs of hours costs about 5 × 10^9. The answer must come from one pass, about 100,000 steps.