Problem Statement
Design a BrowserHistory class that simulates browser navigation:
- visit(url) — Visit a new URL. Clears all forward history.
- back(steps) — Go back
stepsin history. If steps exceed available history, go to the earliest page. Return current URL. - forward(steps) — Go forward
stepsin history. If steps exceed available forward history, go to the most recent page. Return current URL.
Constraints
1 <= url.length <= 201 <= steps <= 100- At most
5000calls tovisit,back,forward - All operations should be O(1) or O(steps)
Example
BrowserHistory history = new BrowserHistory("google.com");
history.visit("facebook.com"); // stack: [google, facebook*]
history.visit("youtube.com"); // stack: [google, facebook, youtube*]
history.back(1); // returns "facebook.com"
history.back(1); // returns "google.com"
history.forward(1); // returns "facebook.com"
history.visit("linkedin.com"); // stack: [google, facebook, linkedin*] — youtube is gone
history.forward(2); // returns "linkedin.com" (can't go forward)
history.back(2); // returns "google.com"
What the Interviewer Expects
- Two approaches: Two stacks (back stack + forward stack) OR doubly linked list with a current pointer.
- visit() clears forward history — this is the key edge case.
- Clamping — back/forward should not go beyond boundaries.
- Clean interface — separate the data structure logic from the navigation logic.
Follow-ups
- How would you persist this history to survive browser restarts?
- How would you implement "recently closed tabs" with undo?
- What if you need to support multiple tabs, each with their own history?
- How would you limit memory usage if the user visits 100K+ pages?