Design Browser History

Medium Design Data Structures Stack

Design Browser History is a medium design data structures problem solved with the stack pattern. The best approach, optimal (one array, a cursor and an end marker), runs in O(1) per call (amortised for visit) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from two stacks up.

Problem

Design the history of a browser tab that starts on a homepage and supports visiting pages and moving back and forward.

  • BrowserHistory(homepage) opens the tab on homepage.
  • visit(url) goes from the current page to url. All the forward history (pages you could have reached with forward) is erased.
  • back(steps) moves back by up to steps pages. If fewer than steps pages are behind you, it stops at the oldest one. It returns the page you end up on.
  • forward(steps) moves forward by up to steps pages. If fewer than steps pages are ahead of you, it stops at the newest one. It returns the page you end up on.

Examples

Example 1

Input
BrowserHistory("home.com"), visit("news.com"), visit("shop.com"), visit("mail.com"), back(1), back(1), forward(1), visit("maps.com"), forward(2), back(2), back(7)
Output
"shop.com", "news.com", "shop.com", "maps.com", "news.com", "home.com"
Why
After three visits the history is home, news, shop, mail and we are on mail. Two backs reach news, one forward returns to shop. Visiting maps.com from shop throws away mail.com, so the history becomes home, news, shop, maps. forward(2) has nowhere to go and stays on maps. back(2) lands on news, and back(7) can only go two more steps, stopping at home.

Example 2

Input
BrowserHistory("a.io"), back(3), forward(1), visit("b.io"), forward(4), back(1)
Output
"a.io", "a.io", "b.io", "a.io"
Why
With only the homepage there is nothing behind or ahead, so back and forward both stay on a.io. After visiting b.io, forward still has nothing ahead, and back(1) returns to a.io.

Constraints

  • 1 <= homepage.length, url.length <= 20
  • 1 <= steps <= 100
  • homepage and url contain only lowercase English letters and '.'.
  • At most 5000 calls in total to visit, back and forward.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Two stacksO(1) amortised for visit, O(min(steps, n)) for back and forwardO(n)
Optimal (one array, a cursor and an end marker)O(1) per call (amortised for visit)O(n)

1Two stacks

TimeO(1) amortised for visit, O(min(steps, n)) for back and forwardback and forward move one page per step and stop early when their stack runs out. Clearing the forward stack costs its size, but each cleared page was pushed there by an earlier step, so it is paid for in advance.
SpaceO(n)The two stacks together hold at most every page visited so far, n of them.

Keep the current page in a variable, the pages behind it on a back stack (newest on top) and the pages ahead of it on a forward stack (nearest on top). Going back one step pushes the current page onto the forward stack and pops the new current page from the back stack; going forward is the mirror image. A visit pushes the current page onto the back stack, makes the url current, and clears the forward stack, because those pages are no longer reachable.

  1. visit(url): push current onto back, set current = url, clear forward.
  2. back(steps): while steps remain and back is not empty, push current onto forward and pop back into current.
  3. forward(steps): while steps remain and forward is not empty, push current onto back and pop forward into current.
  4. back and forward return current.
class BrowserHistory {
    private final Deque<String> backStack = new ArrayDeque<>();
    private final Deque<String> forwardStack = new ArrayDeque<>();
    private String current;

    public BrowserHistory(String homepage) {
        current = homepage;
    }

    public void visit(String url) {
        backStack.push(current);
        current = url;
        forwardStack.clear();
    }

    public String back(int steps) {
        while (steps > 0 && !backStack.isEmpty()) {
            forwardStack.push(current);
            current = backStack.pop();
            steps--;
        }
        return current;
    }

    public String forward(int steps) {
        while (steps > 0 && !forwardStack.isEmpty()) {
            backStack.push(current);
            current = forwardStack.pop();
            steps--;
        }
        return current;
    }
}

2Optimal (one array, a cursor and an end marker)

TimeO(1) per call (amortised for visit)Each call does a constant amount of index arithmetic, plus at most one array write or append.
SpaceO(n)The array never holds more slots than the number of pages visited, n.

Store the whole history in one array and keep two indexes: cur, the page on screen, and last, the newest page that is still reachable. back and forward never change the array; they only move cur, clamped to 0 and last, so each one is a single subtraction or addition. A visit moves cur one step right and writes the url there, overwriting a stale page if one is in that slot, and then sets last = cur, which cuts off the old forward history without deleting anything.

  1. Start with pages = [homepage], cur = 0, last = 0.
  2. visit(url): cur++; if cur is inside the array overwrite pages[cur], otherwise append; then last = cur.
  3. back(steps): cur = max(0, cur - steps); return pages[cur].
  4. forward(steps): cur = min(last, cur + steps); return pages[cur].
class BrowserHistory {
    private final List<String> pages = new ArrayList<>();
    private int cur = 0, last = 0;

    public BrowserHistory(String homepage) {
        pages.add(homepage);
    }

    public void visit(String url) {
        cur++;
        if (cur < pages.size()) pages.set(cur, url);
        else pages.add(url);
        last = cur;
    }

    public String back(int steps) {
        cur = Math.max(0, cur - steps);
        return pages.get(cur);
    }

    public String forward(int steps) {
        cur = Math.min(last, cur + steps);
        return pages.get(cur);
    }
}

Edge cases to test

  • back with more steps than there are pages behind: stop at the homepage
  • forward with more steps than there are pages ahead: stop at the newest page
  • back or forward with nothing on that side: stay where you are
  • visit after going back: every page that was ahead is thrown away
  • Visiting the same url twice in a row: it is stored twice, as two separate entries
  • A long chain of visits followed by back and forward with large step counts

Hints

Hint 1

Think of the pages behind you and the pages ahead of you as two separate piles. Going back moves the current page onto the 'ahead' pile.

Hint 2

Which pile does visit empty?

Hint 3

Instead of moving pages between piles, keep one array of the history and an index for the current page. The only extra thing you need is where the valid history ends, since a visit makes everything after the current page invalid.

FAQ

What is the best time complexity for Design Browser History?

Optimal (one array, a cursor and an end marker) runs in O(1) per call (amortised for visit) time and O(n) extra space. Each call does a constant amount of index arithmetic, plus at most one array write or append.

Which pattern does Design Browser History use?

It is a design data structures problem that uses the stack pattern. Other problems with the same pattern: Min Stack, Design a Stack With Increment Operation, Maximum Frequency Stack.

Is there a brute force solution for Design Browser History?

Yes. Two stacks takes O(1) amortised for visit, O(min(steps, n)) for back and forward time and O(n) space. Keep the current page in a variable, the pages behind it on a back stack (newest on top) and the pages ahead of it on a forward stack (nearest on top).

Which edge cases should I test for Design Browser History?

back with more steps than there are pages behind: stop at the homepage; forward with more steps than there are pages ahead: stop at the newest page; back or forward with nothing on that side: stay where you are; visit after going back: every page that was ahead is thrown away; Visiting the same url twice in a row: it is stored twice, as two separate entries; A long chain of visits followed by back and forward with large step counts.