#1472
Design Browser History
MediumArrayLinked ListStackDesignDoubly-Linked ListData StreamStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) for each operation |
| Space | O(1) | O(n) |
💡
Intuition
Time O(1) for each operationSpace O(n)
Using two stacks allows us to efficiently manage the back and forward history without needing to copy lists. This approach is much faster and uses space effectively.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two stacks: one for back history and one for forward history.
- 2Step 2: For the 'visit' operation, push the current URL onto the back stack, clear the forward stack, and push the new URL onto the back stack.
- 3Step 3: For the 'back' operation, pop from the back stack and push to the forward stack, ensuring we do not exceed the stack size.
- 4Step 4: For the 'forward' operation, pop from the forward stack and push to the back stack, ensuring we do not exceed the stack size.
solution.py21 lines
1# Full working Python code
2class BrowserHistory:
3 def __init__(self, homepage: str):
4 self.back_stack = [homepage]
5 self.forward_stack = []
6
7 def visit(self, url: str) -> None:
8 self.back_stack.append(url)
9 self.forward_stack.clear()
10
11 def back(self, steps: int) -> str:
12 while steps > 0 and len(self.back_stack) > 1:
13 self.forward_stack.append(self.back_stack.pop())
14 steps -= 1
15 return self.back_stack[-1]
16
17 def forward(self, steps: int) -> str:
18 while steps > 0 and self.forward_stack:
19 self.back_stack.append(self.forward_stack.pop())
20 steps -= 1
21 return self.back_stack[-1]ℹ
Complexity note: The time complexity is O(1) for each operation because we are only pushing and popping from stacks. The space complexity is O(n) due to the storage of history in stacks.
- 1Using stacks allows for efficient back and forward navigation.
- 2Clearing the forward history upon visiting a new URL is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.