Per-Tab Navigation Timeline Replay
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate independent per-tab navigation timelines with a cursor, supporting visit, back and forward, and replay a batch of operations to collect their results.
Tab Navigation Replay
A browser keeps a separate navigation timeline for every tab. You are given a recorded list of user actions, and you must replay them in order and report what each one produced.
Each tab has:
- an ordered list of pages it has shown, oldest first, and
- a cursor marking the page currently displayed.
Actions
Every action targets one tab identified by an integer tab_id. Tabs are independent: an action on one tab never changes another tab.
"visit"with arguments[tab_id, url]: the tab navigates tourl.- If the tab has never been used, it starts a new timeline containing only
url. - Otherwise, every page after the cursor (the forward pages) is discarded,
urlis appended, and the cursor moves to it. - The same URL may be visited repeatedly, even consecutively; each visit is stored as its own entry.
- The result for this action is
None.
- If the tab has never been used, it starts a new timeline containing only
"back"with arguments[tab_id]: if the cursor is not on the first page, move it one page toward the oldest. The result is the URL at the cursor after the move. If the cursor was already on the first page, it stays there and that page's URL is returned."forward"with arguments[tab_id]: if there is a page after the cursor, move the cursor one page toward the newest. The result is the URL at the cursor after the move. If the cursor was already on the newest page, it stays there and that page's URL is returned.
If "back" or "forward" targets a tab that has never been visited, the result is the empty string "".
Task
Implement replay_tab_actions(operations, arguments). operations[i] is the action name and arguments[i] is its argument list. Return a list with exactly one result per action, in the same order.
Constraints
len(operations) == len(arguments).operations[i]is one of"visit","back","forward".tab_idis an integer; it may be negative or sparse.- The total number of distinct URLs across all tabs is at most 10^5.
backandforwardshould take O(1) time, andvisitshould take amortized O(1) time.
Examples
Example 1
Input: replay_tab_actions(['visit', 'visit', 'back', 'forward', 'visit', 'forward'], [[1, 'google.com'], [1, 'github.com'], [1], [1], [1, 'stackoverflow.com'], [1]])
Output: [None, None, 'google.com', 'github.com', None, 'stackoverflow.com']
Example 2
Input: replay_tab_actions(['visit', 'visit', 'back', 'back', 'forward', 'forward'], [[7, 'a.com'], [7, 'b.com'], [7], [7], [7], [7]])
Output: [None, None, 'a.com', 'a.com', 'b.com', 'b.com']
Example 3
Input: replay_tab_actions(['visit', 'visit', 'visit', 'back', 'forward', 'back', 'back', 'forward'], [[1, 'one.com'], [2, 'two.com'], [1, 'three.com'], [1], [2], [1], [1], [1]])
Output: [None, None, None, 'one.com', 'two.com', 'one.com', 'one.com', 'three.com']
Hints
Hint 1
Think of each tab as a single list of pages plus one integer cursor, rather than two separate stacks.
Hint 2
Store the per-tab state in a dictionary keyed by tab_id so tabs never interfere, and treat a tab that is not in the dictionary as a special case for back and forward.
Hint 3
On a visit, cut the list off right after the cursor before appending the new URL. Each entry is added once and removed at most once, which gives amortized O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each tab as one list of pages (oldest first) plus an integer cursor. Everything before the cursor is the back path and everything after it is the forward path, so no second stack is needed. A dictionary maps each tab_id to its [pages, cursor] pair, which keeps tabs completely independent.
- visit: for a new tab, create
[[url], 0]. Otherwise delete every entry after the cursor, appendurl, and set the cursor to the last index. RecordNone. - back: if the tab is unknown, record
"". Otherwise decrement the cursor if it is above 0, then record the page at the cursor. - forward: if the tab is unknown, record
"". Otherwise increment the cursor if a later page exists, then record the page at the cursor.
Why it is correct
The invariant is that pages[:cursor] is exactly the back path, pages[cursor] is the current page, and pages[cursor+1:] is exactly the forward path.
backandforwardonly move the cursor within bounds and never change the list, so going back and then forward returns to the same page.visittruncates the list after the cursor, which discards all forward pages (not just one), then appends the new page as the newest entry. The forward path is therefore empty afterward, soforwardright after avisitreturns the page just visited.- Different tabs live under different dictionary keys, so they never share state. Using a dictionary also makes negative or sparse ids safe.
Complexity
backandforward: O(1) each (one dictionary lookup, one bounds check, one index read).visit: amortized O(1). Truncation costs time proportional to the number of removed entries, but each entry is appended once and removed at most once, so total removal work is bounded by the number of visits.- Whole replay: O(n) time for n actions. Space is O(E), where E is the number of entries currently retained plus the number of tabs.
Reference solution
from typing import List, Optional
def replay_tab_actions(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
# tab_id -> [pages, cursor]
tabs = {}
results: List[Optional[str]] = []
for operation, args in zip(operations, arguments):
if operation == "visit":
tab_id, url = args
if tab_id not in tabs:
tabs[tab_id] = [[url], 0]
else:
pages, cursor = tabs[tab_id]
del pages[cursor + 1:]
pages.append(url)
tabs[tab_id][1] = len(pages) - 1
results.append(None)
elif operation == "back":
tab_id = args[0]
if tab_id not in tabs:
results.append("")
continue
pages, cursor = tabs[tab_id]
if cursor > 0:
cursor -= 1
tabs[tab_id][1] = cursor
results.append(pages[cursor])
elif operation == "forward":
tab_id = args[0]
if tab_id not in tabs:
results.append("")
continue
pages, cursor = tabs[tab_id]
if cursor + 1 < len(pages):
cursor += 1
tabs[tab_id][1] = cursor
results.append(pages[cursor])
return results