Lowest Point on the Trail

MediumdesignAlso known as Min Stack

A hiking app records your route as a list of waypoint altitudes. Walking forward adds a waypoint. Retracing your steps from a dead end drops the waypoints you walk back over, so the list is always your path from the trailhead.

The screen shows your current altitude and the lowest altitude on your current path, refreshed after every step, so both values must be available instantly, even with thousands of waypoints.

Your task

Write a class TrailLog:

  • step(altitude) adds a waypoint at the end of the path.
  • back() removes the most recent waypoint.
  • current() returns the altitude of the most recent waypoint.
  • lowest() returns 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 and then 410 m, so the lowest altitude is 280. Backing off 410 does not change the lowest, but backing off 280 as well leaves only 340, so both lowest and current return 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 altitudes in an array and scan it on every lowest() call. That is O(n) per call and O(n²) over a hike of n waypoints.

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