AlgoInsight

DSA problem

Design Browser History

MediumData Structure DesignPattern: Data Structure Designtop150FreeAmazonMicrosoftGoogleBloombergApple

You have a browser of one tab where you start on the homepage and you can visit another URL, get back in the history a number of steps, or move forward in the history. Implement the BrowserHistory class to model this behaviour with three operations.

BrowserHistory(homepage) initializes the object with the homepage as the only entry in history. visit(url) visits url from the current page — this clears all forward history. back(steps) moves steps back in history; if you can only go x < steps back, you stop at the earliest reachable page; returns the current URL. forward(steps) moves steps forward; similarly clamped to the most recent visited URL; returns the current URL.

The cleanest backing structure is a dynamic array that holds the entire history along with two pointers: currentIdx (the index of the page you are on) and len (the logical length, i.e., one past the most recent visit reachable by forward). A visit writes the new URL at currentIdx + 1 (resizing the array if needed) and sets both currentIdx and len to that new position, which effectively truncates forward history. back and forward shift currentIdx by the requested amount, clamped to [0, len - 1].

This gives O(1) per operation. An alternative is two stacks (back/forward), which has the same asymptotic complexity but is harder to clamp correctly. The array approach is the implementation most browsers actually use internally.

Examples

Example 1
Input: ["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"] [["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output: [null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Explanation: You start at leetcode.com, then visit three sites. back(1) goes to facebook.com; back(1) goes to google.com; forward(1) returns to facebook.com. visit(linkedin.com) overwrites the forward history. forward(2) is clamped to linkedin.com. back(2) goes to google.com, back(7) is clamped to leetcode.com.
Example 2
Input: ["BrowserHistory","visit","back","forward"] [["a.com"],["b.com"],[1],[1]]
Output: [null,null,"a.com","b.com"]
Explanation: After visiting b.com, back(1) returns to a.com and forward(1) returns to b.com.
Example 3
Input: ["BrowserHistory","back","forward"] [["start.com"],[5],[5]]
Output: [null,"start.com","start.com"]
Explanation: With only the homepage in history, both back and forward are clamped to start.com.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraylinked-listdesignstackdoubly-linked-listdata-stream

Browse all DSA problems