Lowest Point on the Trail

MediumdesignAlso known as Min Stack

A hiking app records your route as a list of waypoints, each with its altitude. Walking forward adds a waypoint. When you hit a dead end and retrace your steps, the app drops the waypoints you walk back over, so the list is always the path from the trailhead to where you stand.

The app shows two numbers on screen at all times: your current altitude and the lowest altitude on your current path. They are refreshed after every step, so each must be instant, even on a path with thousands of waypoints.

Your task

Write a class TrailLog with these methods:

  • step(altitude): add a waypoint at the end of the path.
  • back(): remove the most recent waypoint.
  • current(): return the altitude of the most recent waypoint.
  • lowest(): return the lowest altitude among all waypoints still on the path.

Every method must run in O(1) time.

class TrailLog

Examples

Example 1
Input
new TrailLog()
.step(340)
.step(280)
.step(410)
.lowest()
.back()
.back()
.lowest()
.current()
Output
[null, null, null, null, 280, null, null, 340, 340]
Why

The hiker walks to 340 m, 280 m, then 410 m. The lowest point on the path is 280. Backing off 410 changes nothing, but backing off 280 too leaves only 340 on the path, so the lowest point is now 340 and the hiker stands at 340.

Constraints

  • 1 ≤ number of method calls ≤ 1,000
  • -1,000 ≤ altitude ≤ 10,000 (metres; negative means below sea level). Altitudes may repeat.
  • back, current and lowest are only called when the path has at least one waypoint.
Start with brute force

Keep the altitudes in an array and compute lowest() by scanning the whole array each time it is called.

That makes lowest() O(n). The screen refreshes after every step, so a hike of n waypoints costs O(n²) in total. A single low variable is fast but wrong: it cannot recover the previous low after back() removes the lowest waypoint.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code