Maps app~15 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-496monotonic-stack · stacks
A hiking app stores the elevation of every waypoint along a trail, in metres, in walking order. All the elevations are different.
A hiker marks a few waypoints as viewpoints. For each viewpoint, the app shows the elevation of the next waypoint further along the trail that is higher. That tells the hiker whether a climb is ahead.
If the trail never rises above a viewpoint again, the app shows -1. A trail can have up to 100,000 waypoints.
Write next_higher_point(viewpoints, trail).
trail is a list of whole numbers: the elevations of the waypoints, in walking order. No two are equal.viewpoints is a list of different elevations. Each one is the elevation of a waypoint on the trail.-1 if there is none.viewpoints.Input: viewpoints = [180, 310, 640, 420], trail = [420, 180, 250, 640, 310, 90, 500]
Output: [250, 500, -1, 640]Read the trail once. A stack holds the elevations still waiting for a higher waypoint, and a table remembers each answer. When a waypoint arrives, it answers every waiting elevation lower than itself.
| Waypoint read | Elevations popped (and their answer) | Waiting stack after |
|---|---|---|
| 420 | none | 420 |
| 180 | none | 420, 180 |
| 250 | 180: answer 250 | 420, 250 |
| 640 | 250: answer 640, 420: answer 640 | 640 |
| 310 | none | 640, 310 |
| 90 | none | 640, 310, 90 |
| 500 | 90: answer 500, 310: answer 500 | 640, 500 |
Waypoints 640 and 500 were still waiting at the end, so their answer is -1. The viewpoints are then read from the table: 180 gives 250, 310 gives 500, 640 gives -1 and 420 gives 640.
Input: viewpoints = [300, 100], trail = [100, 200, 300]
Output: [-1, 200]Waypoint 300 is the last one, so nothing comes after it. Waypoint 100 is followed by 200, which is higher.
Input: viewpoints = [800], trail = [900, 800, 700]
Output: [-1]The trail only falls, so no viewpoint has a higher waypoint ahead.
1 ≤ number of waypoints ≤ 10^51 ≤ each elevation ≤ 10^6, and no two elevations are equal1 ≤ number of viewpoints ≤ number of waypoints, and every viewpoint is an elevation on the trailA plan that finds each viewpoint on the trail and then scans forward costs up to n steps for every viewpoint. With 100,000 viewpoints that is about 10^10 steps. It is too slow.
So the trail must be read in one pass, and each waypoint handled a constant number of times. The viewpoints are answered afterwards, from a table.