Design Browser History — LeetCode 1472 Python Solution
- Problem
- #1472
- Pattern
- Linked List
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
Example
- Input
- ["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
- Output
- [null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
- Explanation
- BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
Python solution
class BrowserHistory:
def __init__(self, homepage: str):
self.stk1 = []
self.stk2 = []
self.visit(homepage)
def visit(self, url: str) -> None:
self.stk1.append(url)
self.stk2.clear()
def back(self, steps: int) -> str:
while steps and len(self.stk1) > 1:
self.stk2.append(self.stk1.pop())
steps -= 1
return self.stk1[-1]
def forward(self, steps: int) -> str:
while steps and self.stk2:
self.stk1.append(self.stk2.pop())
steps -= 1
return self.stk1[-1]
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)Complexity
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(n), where n is the length of the browsing history auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1472. Design Browser History is filed here because LeetCode tags it Linked List and Doubly-Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1472. Design Browser History?
- LeetCode 1472. Design Browser History is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1472. Design Browser History?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 1472. Design Browser History?
- The Python solution on this page uses O(n), where n is the length of the browsing history auxiliary space.
- What topics does LeetCode 1472. Design Browser History cover?
- LeetCode 1472. Design Browser History is tagged Stack, Design, Array, Linked List, Data Stream and Doubly-Linked List on LeetCode.