Skip to content

Current URL with Forward

01 · Question

Extend Current URL with forward(k), which reverses back navigation up to k times. Forward beyond the newest reachable page does nothing. Every go action clears forward history, even when revisiting the same URL. The first action is go; back/forward counts are positive.

Example: go A, go B, back 1, forward 1, back 3, go C, forward 3 → C.

02 · Analysis

History's top is current; forward's top is the next page that can be restored. On back, move the history top to forward, keeping one page. On forward, transfer in the opposite direction. On go, push the new URL and clear forward.

Two-stack implementation: O(n + M) time and O(n) space, for n actions and M actual page transfers. Unlike back-only navigation, the same pages can move repeatedly; M may be quadratic in n. Clearing forward also has a cost, but each entry can be discarded only once per visit. An alternative history array plus cursor can clamp multi-step back/forward using index arithmetic.

03 · Solution

Reference solution

1def current_url_with_forward(actions):
2 history, forward = [], []
3 for kind, value in actions:
4 if kind == "go":
5 history.append(value)
6 forward.clear()
7 elif kind == "back":
8 while value > 0 and len(history) > 1:
9 forward.append(history.pop())
10 value -= 1
11 else:
12 while value > 0 and forward:
13 history.append(forward.pop())
14 value -= 1
15 return history[-1]