Design Browser History — Stack-Based Navigation

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem

Implement browser history:

  • BrowserHistory(homepage) — start at homepage
  • visit(url) — go to url, clear forward history
  • back(steps) — go back up to steps pages, return current url
  • forward(steps) — go forward up to steps pages, return current url

Solutions

Python

class BrowserHistory:
    def __init__(self, homepage: str):
        self.history = [homepage]
        self.idx = 0

    def visit(self, url: str) -> None:
        self.history = self.history[:self.idx + 1]
        self.history.append(url)
        self.idx += 1

    def back(self, steps: int) -> str:
        self.idx = max(0, self.idx - steps)
        return self.history[self.idx]

    def forward(self, steps: int) -> str:
        self.idx = min(len(self.history) - 1, self.idx + steps)
        return self.history[self.idx]

JavaScript

class BrowserHistory {
    constructor(homepage) { this.h = [homepage]; this.i = 0; }
    visit(url) { this.h = this.h.slice(0, this.i + 1); this.h.push(url); this.i++; }
    back(steps) { this.i = Math.max(0, this.i - steps); return this.h[this.i]; }
    forward(steps) { this.i = Math.min(this.h.length - 1, this.i + steps); return this.h[this.i]; }
}

Java

import java.util.*;
class BrowserHistory {
    List<String> h = new ArrayList<>(); int i = 0;
    public BrowserHistory(String homepage) { h.add(homepage); }
    public void visit(String url) {
        while (h.size() > i + 1) h.remove(h.size() - 1);
        h.add(url); i++;
    }
    public String back(int steps) { i = Math.max(0, i - steps); return h.get(i); }
    public String forward(int steps) { i = Math.min(h.size()-1, i+steps); return h.get(i); }
}

C++

#include <vector>
#include <string>
using namespace std;
class BrowserHistory {
    vector<string> h; int i = 0;
public:
    BrowserHistory(string homepage) { h.push_back(homepage); }
    void visit(string url) { h.resize(i + 1); h.push_back(url); i++; }
    string back(int steps) { i = max(0, i - steps); return h[i]; }
    string forward(int steps) { i = min((int)h.size()-1, i+steps); return h[i]; }
};

C

char history[500][200]; int idx = 0, top = 0;
void visit(char* url) { idx++; top = idx; strcpy(history[idx], url); }
char* back(int steps) { idx = idx-steps > 0 ? idx-steps : 0; return history[idx]; }
char* fwd(int steps) { idx = idx+steps < top ? idx+steps : top; return history[idx]; }

Complexity

OperationTimeSpace
visitO(1) amortisedO(N)
back / forwardO(steps)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro