Problem statement

https://binarysearch.com/problems/Web-Browser/

Solution

Equal to Leetcode 1472. Design Browser History.

Complexity

It is O(1) for time for all operations. It is O(n) for space.

Code

class WebBrowser:
    def __init__(self, homepage):
        self.stack = [homepage]
        self.curr = 0
        self.end = 0

    def visit(self, url):
        if self.curr + 1 >= len(self.stack):
            self.stack += [""]
        self.stack[self.curr + 1] = url
        self.curr += 1
        self.end = self.curr

    def back(self, steps):
        self.curr = max(0, self.curr - steps)
        return self.stack[self.curr]
        
    def forward(self, steps):
        self.curr = min(self.end, self.curr + steps)
        return self.stack[self.curr]