Doubly Linked List

Design Browser History

Medium
Solve it on LeetCode ↗

The problem

Implement visit(url) (clearing forward history), back(steps), and forward(steps) for a browser starting on a homepage.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Keep a current node with prev/next pointers.
  2. 2visit: create a node, link current.next = node, node.prev = current, move current (old forward chain is now unreachable).
  3. 3back(steps): follow prev up to steps times or until the front.
  4. 4forward(steps): follow next symmetrically. Return the landing URL.

Key insight

Setting current.next to the new page implicitly garbage-collects the entire forward branch — no explicit clearing needed.

The solution

Watch out for

  • back/forward must clamp at the ends, not error.
  • With the array model, visit() must truncate everything after the pointer before appending.