Design Browser History — Stack-Based Navigation
Advertisement
Problem
Implement browser history:
BrowserHistory(homepage)— start at homepagevisit(url)— go to url, clear forward historyback(steps)— go back up tostepspages, return current urlforward(steps)— go forward up tostepspages, 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
| Operation | Time | Space |
|---|---|---|
| visit | O(1) amortised | O(N) |
| back / forward | O(steps) | — |
Advertisement