MediumPythonJavaScriptTypeScript
Browser History with Doubly Linked List
Data StructuresLinked ListDesign
Implement a browser history navigator backed by a doubly linked list.
Each node holds a URL and two pointers (prev, next). The cursor always
points at the current page. Visiting a new URL appends a node after the
cursor and discards everything forward (just like a real browser).
API
class BrowserHistory {
constructor(homepage) // start on this URL
visit(url) // move forward; drop all forward history
back(steps) // move backward up to `steps` pages; return current URL
forward(steps) // move forward up to `steps` pages; return current URL
}solve(homepage, ops) replays operations and returns the current URL after
every back and forward call (visit produces null in the output).
Example
solve('home.com', [
['visit', 'a.com'],
['visit', 'b.com'],
['back', 1], // → 'a.com'
['back', 1], // → 'home.com'
['forward', 1], // → 'a.com'
['visit', 'c.com'], // → null (b.com is now gone)
['forward', 100], // → 'c.com' (already at end)
['back', 2], // → 'home.com'
])
// output: [null, null, 'a.com', 'home.com', 'a.com', null, 'c.com', 'home.com']Constraints
- Steps may exceed the available history in either direction — clamp at the
boundary.
- The internal
DListNodemust carry bothprevandnextpointers.
Sample tests
Test #1Full navigation scenario — visit clears forward history
Input: ["home.com",[["visit","a.com"],["visit","b.com"],["back",1],["back",1],["forward",1],["visit","c.com"],["forward",100],["back",2]]]
Output: [null,null,"a.com","home.com","a.com",null,"c.com","home.com"]
Test #2back/forward on single-node history — always returns homepage
Input: ["start.com",[["back",5],["forward",5]]]
Output: ["start.com","start.com"]
Test #3Visiting mid-history drops c.com; forward clamps at d.com
Input: ["a.com",[["visit","b.com"],["visit","c.com"],["back",1],["visit","d.com"],["forward",10],["back",1]]]
Output: [null,null,"b.com",null,"d.com","b.com"]