I am trying to solve this Leetcode question: https://leetcode.com/problems/design-browser-history/
Below is my code:
class BrowserHistory:
def __init__(self, homepage: str):
self.history = []
self.history.append(homepage)
self.currPos = 0
def visit(self, url: str) -> None:
self.history.append(url)
self.currPos = len(self.history) - 1
def back(self, steps: int) -> str:
pos = self.currPos - steps
if pos <= 0:
self.currPos = 0
return self.history[0]
else:
self.currPos = pos
return self.history[pos]
def forward(self, steps: int) -> str:
pos2 = self.currPos + steps
if pos2 >= len(self.history) - 1:
self.currPos = len(self.history) - 1
return self.history[-1]
else:
self.currPos = pos2
return self.history[pos2]
When I run this, the sample usecase is failing:
INPUT:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
OUTPUT:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","facebook.com","leetcode.com"]
EXPECTED OUTPUT:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Not sure why back of 2 steps should give google.com instead of facebook.com.
Where am I going wrong? Any help would be appreciated.
Thank you.