Design Browser History

Keep a browser's back and forward history in one list, with two indexes that make every call a single step.

Write a class that keeps the history of one browser tab. The constructor takes the homepage, which is the page shown at the start. The class has three methods:

Example 1
Input: BrowserHistory("home.example"), visit("news.example"), visit("maps.example"), visit("video.example"), back(1), back(1), forward(1), visit("shop.example"), forward(2), back(2), back(7)
Output: "maps.example", "news.example", "maps.example", "shop.example", "news.example", "home.example"

The output lists only the values that back and forward return, in order; the constructor and visit return nothing.

Solution

The Idea

Every web browser has a back button and a forward button. Back returns to the page you were on before, and forward undoes a back. This class keeps the list of pages behind those two buttons.

Follow Example 1. The tab starts on home.example and visits news.example, maps.example and video.example, so four pages now stand in order with video.example on screen. Then back(1) shows maps.example, a second back(1) shows news.example, and forward(1) returns to maps.example. So far nothing is forgotten: video.example is still one step ahead.

Then comes visit("shop.example"), opened from maps.example. What happens to video.example? A real browser drops it, and its forward button turns grey. That is why forward(2) stays on shop.example: nothing is ahead of it any more. So how should the class store the pages, and how can it forget the pages ahead cheaply?

Keep the pages in one list, in the order they were reached. Number the places in the list from 0 and call each one a slot. A number named cur holds the slot on screen, so back and forward only change cur. A second number, last, holds the slot of the newest page that forward may still reach. The picture shows both numbers just before and just after the visit.

The history as slots 0 to 3. Top row, after back(1), back(1), forward(1): home, news, maps and video, with cur on maps in slot 2 and last on video in slot 3. Bottom row, after visit("shop.example"): slot 3 holds shop.example, which was video.example, and cur and last both point at slot 3.

In the top row, labelled after back(1), back(1), forward(1), cur points at maps.example in slot 2 and last at video.example in slot 3. In the bottom row, the visit has moved cur one slot on, to slot 3. It wrote shop.example there, over video.example, and set last to the same slot.

So a visit never has to delete pages. It writes into the slot after cur and sets last to that slot, and forward cannot pass last.

Solution Approach

With the list, cur and last in place, three questions remain: how to handle a step count that goes too far, what a visit does with the pages ahead of cur, and whether two piles of pages would be a simpler design.

Step counts that go too far

What should back(7) do when only one page lies behind? The problem says back goes at most steps pages and stops at the homepage, in slot 0. A loop that moves one slot at a time and stops at slot 0 would work, but it runs once per step asked for.

One line of arithmetic in each method gives the same slot at once. The method back sets cur to Math.max(0, cur - steps), and forward sets it to Math.min(last, cur + steps). In Example 1, back(7) starts from slot 1, and Math.max(0, 1 - 7) is 0, so it returns home.example.

Forgetting the pages ahead

Which pages should forward reach after a visit? Only the pages up to the new one. The direct way is to delete every slot after cur, for example with pages.subList(cur + 1, pages.size()).clear(). That is correct, but the list has to clear every dropped slot, so a visit after a long back costs one step per dropped page.

Moving last costs one step however many pages are dropped. Old pages may still sit in the list after last, but forward never passes last, so they cannot come back. The next visit that lands on one of those slots writes over it.

Two piles instead of one list

Could two piles of pages do the same job? In the top row of the picture, one pile would hold home.example and news.example, with news.example on top as the page back(1) shows. The other pile would hold video.example, the page forward(1) shows. Piles like these, where back(1) takes the page on top, are called stacks.

That design is correct too: back moves pages from the first stack to the second, forward moves them the other way, and a visit empties the forward stack. But back(7) moves pages one at a time, and a visit pays one step per page it throws away. The list with cur and last does each call in one step.

Java Solution

The class DesignBrowserHistory has these parts:

  • pages: the list of slots, an ArrayList that starts with the homepage in slot 0.
  • cur: the slot of the page on screen. The methods back and forward move it with Math.max and Math.min and return the page in that slot.
  • last: the slot of the newest page that forward may reach.
  • visit: moves cur one slot on and writes the URL there, with set when the slot already exists and add when the list must grow. Then it sets last to cur.

The main method runs Example 1, then tries forward(5) and back(5) on a fresh history, then goes back two pages before a visit, so that an old page stays in the list after last.

Java
import java.util.ArrayList;
import java.util.List;

public class DesignBrowserHistory {

    private final List<String> pages = new ArrayList<>();
    private int cur = 0;   // slot of the page being shown
    private int last = 0;  // slot of the newest page that forward may reach

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

    public void visit(String url) {
        cur++;
        if (cur < pages.size()) {
            pages.set(cur, url);   // reuse the slot of an old forward page
        } else {
            pages.add(url);        // the list is full: grow it by one
        }
        last = cur;                // pages after the new one are no longer reachable
    }

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

    public String forward(int steps) {
        cur = Math.min(last, cur + steps);    // never past the newest reachable page
        return pages.get(cur);
    }

    public static void main(String[] args) {
        DesignBrowserHistory h = new DesignBrowserHistory("home.example");
        h.visit("news.example");
        h.visit("maps.example");
        h.visit("video.example");
        System.out.println("back(1) -> " + h.back(1));
        System.out.println("back(1) -> " + h.back(1));
        System.out.println("forward(1) -> " + h.forward(1));
        h.visit("shop.example");
        System.out.println("forward(2) -> " + h.forward(2));
        System.out.println("back(2) -> " + h.back(2));
        System.out.println("back(7) -> " + h.back(7));

        DesignBrowserHistory fresh = new DesignBrowserHistory("home.example");
        System.out.println("fresh: forward(5) -> " + fresh.forward(5)
                + ", back(5) -> " + fresh.back(5));

        DesignBrowserHistory cut = new DesignBrowserHistory("home.example");
        cut.visit("news.example");
        cut.visit("maps.example");
        cut.visit("video.example");
        System.out.println("cut: back(2) -> " + cut.back(2));
        cut.visit("shop.example");
        System.out.println("cut: forward(1) -> " + cut.forward(1)
                + ", list still holds " + cut.pages);
    }
}

Running it prints:

Output
back(1) -> maps.example
back(1) -> news.example
forward(1) -> maps.example
forward(2) -> shop.example
back(2) -> news.example
back(7) -> home.example
fresh: forward(5) -> home.example, back(5) -> home.example
cut: back(2) -> news.example
cut: forward(1) -> shop.example, list still holds [home.example, news.example, shop.example, video.example]

The six lines from back(1) -> maps.example to back(7) -> home.example are the outputs of Example 1, in order. In forward(2) -> shop.example, the visit has left nothing ahead, so cur stays on slot 3. The fresh: line shows that a history holding only the homepage returns home.example for any step count, since cur and last both start at 0.

Now look at the last line. After back(2) from video.example, the visit wrote shop.example into slot 2, yet video.example is still in slot 3 of the list. Still, forward(1) returns shop.example, because last is 2. A version whose forward stops at the end of the list, pages.size() - 1, gets this wrong: run on the same calls, it printed forward(1) -> video.example, a page the visit should have dropped.

Complexity

Each call does a fixed amount of work, however many pages the history holds and however large steps is.

  • Time: O(1) per call, because back and forward compute the new slot with one Math.max or Math.min and read one slot, and visit writes one slot. Now and then add has to make room for more slots, but the ArrayList documentation promises that this averages out to constant time per add.
  • Space: O(v) for v calls to visit, because the list holds the homepage plus at most one new slot per visit, and dropped pages keep their slots until a later visit writes over them.

For a class that is built on a stack, see Min Stack.