Project · Stack

Browser
History

Every browser back/forward button is powered by two stacks. One holds the pages you can go back to, the other holds the pages you can go forward to. Both operations are O(1).

Dual-stack architecture

// after visiting A → B → C, pressing Back twice
backStack [ A ] top
currentPage B
forwardStack [ C ] top
pressing Back: pop from backStack → push current to forwardStack
pressing Forward: pop from forwardStack → push current to backStack

Visit a new page

visit
1function visit(url):
2 backStack.push(url) // save current to back
3 forwardStack.clear() // new visit erases forward history
4 currentPage = url

Go back

go-back
1function goBack():
2 if backStack.isEmpty(): return // nothing to go back to
3 forwardStack.push(currentPage) // save current to forward
4 currentPage = backStack.pop()

Go forward

go-forward
1function goForward():
2 if forwardStack.isEmpty(): return
3 backStack.push(currentPage)
4 currentPage = forwardStack.pop()

Navigation walkthrough

1 / 4
1

Visit A, B, C

back = [A, B, C], forward = [], current = C. Each visit pushes to backStack and clears forwardStack. The stack grows to hold the full back history.

1 of 4

Time complexity

Visit new page — push + clear forward stackO(1)

Constant time

Go back — pop back stack, push forward stackO(1)

Constant time

Go forward — pop forward stack, push back stackO(1)

Constant time

Space — n = total history lengthO(n)

Linear time

The critical rule

Visiting clears forward
When you visit a new page, the forward stack is cleared. You cannot go forward from a newly visited page — this matches every browser you have ever used.
Back stack grows on visit
Every visit pushes to the back stack. The back button is available immediately after any navigation.
🔍Why not a doubly linked list?
A doubly linked list can also support O(1) back/forward. But the two-stack pattern is simpler to reason about: each stack is independently ordered by time. When you visit a new page you simply clear one stack — no pointer surgery needed.

🎯 Quick Check

You visit pages A → B → C. You go back twice (now at A). You then visit D. What is the forward stack?