Skip to content

Current URL

01 · Question

Process a nonempty action list whose first action is go. A go action visits a URL; back(k) moves back up to k pages, where k ≥ 1. Moving beyond the first page leaves you there. Return the current URL.

Example: go A, go B, go C, back 4, go D, go E, back 1 → D.

Python actions are (kind, URL-or-count) pairs. Go uses Action records; set URL for go and Steps for back.

02 · Analysis

Invariant: the stack contains the active history, with the current page at the top. Push on go and pop on back while the stack has more than one item. Do not pop the initial page.

For n actions, O(n) total time and O(n) space: each go adds one entry and each entry can be popped at most once. Even an enormous back count stops at the first page.

03 · Solution

Reference solution

1def current_url(actions):
2 history = []
3 for kind, value in actions:
4 if kind == "go":
5 history.append(value)
6 else:
7 while value > 0 and len(history) > 1:
8 history.pop()
9 value -= 1
10 return history[-1]