Design Browser History
Problem
Implement visit(url), back(steps), forward(steps) for a single-tab browser history starting at a homepage.
"leetcode" → visit "google" → visit "fb" → visit "yt" → back 1 → back 1 → forward 1 → visit "linkedin" → forward 2 → back 2 → back 7"google" "fb" "linkedin" "leetcode"class BrowserHistory:
def __init__(self, homepage):
self.h = [homepage]; self.cur = 0
def visit(self, url):
self.h = self.h[:self.cur + 1]
self.h.append(url); self.cur += 1
def back(self, steps):
self.cur = max(0, self.cur - steps)
return self.h[self.cur]
def forward(self, steps):
self.cur = min(len(self.h) - 1, self.cur + steps)
return self.h[self.cur]
class BrowserHistory {
constructor(homepage) { this.h = [homepage]; this.cur = 0; }
visit(url) { this.h.length = this.cur + 1; this.h.push(url); this.cur++; }
back(steps) { this.cur = Math.max(0, this.cur - steps); return this.h[this.cur]; }
forward(steps) { this.cur = Math.min(this.h.length - 1, this.cur + steps); return this.h[this.cur]; }
}
class BrowserHistory {
List h = new ArrayList<>(); int cur = 0;
public BrowserHistory(String homepage) { h.add(homepage); }
public void visit(String url) {
while (h.size() > cur + 1) h.remove(h.size() - 1);
h.add(url); cur++;
}
public String back(int steps) { cur = Math.max(0, cur - steps); return h.get(cur); }
public String forward(int steps) { cur = Math.min(h.size() - 1, cur + steps); return h.get(cur); }
}
class BrowserHistory {
vector h; int cur = 0;
public:
BrowserHistory(string homepage) { h.push_back(homepage); }
void visit(string url) { h.resize(cur + 1); h.push_back(url); cur++; }
string back(int steps) { cur = max(0, cur - steps); return h[cur]; }
string forward(int steps) { cur = min((int)h.size() - 1, cur + steps); return h[cur]; }
};
Explanation
A single-tab browser history is just a list of pages plus a pointer to where you currently are. Going back or forward only moves the pointer; visiting a new page wipes out everything ahead of it. This solution stores the pages in self.h and the position in self.cur.
visit(url) first does self.h = self.h[:self.cur + 1] to truncate the forward history — once you visit a fresh page, the pages you could have gone forward to are gone. Then it appends the new url and advances self.cur.
back(steps) moves the pointer left but never past the homepage, using max(0, self.cur - steps). forward(steps) moves it right but never past the newest page, using min(len(self.h) - 1, self.cur + steps). The clamping is what makes over-stepping safe — asking to go back 7 just lands you at the start.
Example: after visiting google, fb, yt, the list is [leetcode, google, fb, yt] with cur at yt. back(1) → fb, back(1) → google, forward(1) → fb, then visit("linkedin") truncates yt and appends linkedin. A later back(7) clamps all the way to leetcode.