Design browser history across tabs
ChimeBackend Engineer · Technical ScreenLast updated
This question tests the ability to design an efficient data structure for navigating browser history, requiring careful management of back/forward states across multiple independent tabs.
Browser History Manager
Design a system to track browser history for multiple tabs. Each tab acts as an independent stack of visited URLs. You need to support navigation, jumping back and forth in time, and visiting new pages.
Requirements
Implement a class BrowserSession with the following methods:
visit(tab_id: int, url: str): The user visits a new URL. This clears all 'forward' history for the current tab.back(tab_id: int) -> str: Moves the user back to the previous URL in the tab. Returns the new current URL, or the current URL if no history exists.forward(tab_id: int) -> str: Moves the user forward to the next URL (if available after a 'back' operation). Returns the new current URL.
Constraints
tab_idis an integer.- Total number of unique URLs across all tabs is at most 10^5.
backandforwardoperations should run in O(1) time.visitshould run in O(1) time (amortized).
Examples
# Initial state
session = BrowserSession()
session.visit(1, "google.com")
session.visit(1, "github.com")
session.back(1) # Returns "google.com"
session.forward(1) # Returns "github.com"
session.visit(1, "stackoverflow.com")
session.forward(1) # Returns "stackoverflow.com" (nothing forward)
Edge Cases
- Calling
backwhen on the first page. - Calling
forwardafter a newvisit. - Handling multiple
tab_ids that maintain separate histories.
Hints
Hint 1
Consider using two stacks for each tab: one for the backward history and one for the forward history.
Hint 2
When a new URL is visited, the forward stack for that specific tab must be cleared to represent a new branch in navigation.
Hint 3
Use a hash map (dictionary) where the key is the `tab_id` and the value is a custom object or pair of stacks representing that tab's state.
Follow-up questions
- How would you modify your design if you needed to limit the maximum history length to 50 URLs per tab?
- If this were a distributed system where history needs to persist across device reboots, what database schema would you use?
- How would you implement a 'global' search to find if a URL exists in any of the active tab histories?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.