SDE & MLE Prep

1472. Design Browser History

Problem

Design BrowserHistory(homepage) for a single tab: visit(url) opens url and clears all forward history, back(steps) and forward(steps) move at most steps pages (stopping at either end) and return the current URL.

Example: home "a.com", visit b, c, d → back(1) = "c", back(1) = "b", forward(1) = "c", visit e → forward(2) = "e", back(2) = "b", back(7) = "a.com"

Array of pages + cur index + last (the end of the valid forward history). visit overwrites at cur+1 and truncates forward history by setting last = cur.

Complexity: O(1) per operation.

class BrowserHistory:
    def __init__(self, homepage: str):
        self.pages, self.cur, self.last = [homepage], 0, 0

    def visit(self, url: str) -> None:
        self.cur += 1
        if self.cur == len(self.pages):
            self.pages.append(url)
        else:
            self.pages[self.cur] = url
        self.last = self.cur

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

    def forward(self, steps: int) -> str:
        self.cur = min(self.last, self.cur + steps)
        return self.pages[self.cur]