Katkat

Design browser history across tabs

ChimeBackend Engineer · Technical Screen

Last 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:

  1. visit(tab_id: int, url: str): The user visits a new URL. This clears all 'forward' history for the current tab.
  2. 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.
  3. 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_id is an integer.
  • Total number of unique URLs across all tabs is at most 10^5.
  • back and forward operations should run in O(1) time.
  • visit should 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 back when on the first page.
  • Calling forward after a new visit.
  • 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?