|
| 1 | +# Linked List Implementation |
| 2 | +class ListNode: |
| 3 | + def __init__(self, val, prev=None, next=None): |
| 4 | + self.val = val |
| 5 | + self.prev = prev |
| 6 | + self.next = next |
| 7 | + |
| 8 | +class BrowserHistory: |
| 9 | + |
| 10 | + def __init__(self, homepage: str): |
| 11 | + self.cur = ListNode(homepage) |
| 12 | + |
| 13 | + # O(1) |
| 14 | + def visit(self, url: str) -> None: |
| 15 | + self.cur.next = ListNode(url, self.cur) |
| 16 | + self.cur = self.cur.next |
| 17 | + |
| 18 | + # O(n) |
| 19 | + def back(self, steps: int) -> str: |
| 20 | + while self.cur.prev and steps > 0: |
| 21 | + self.cur = self.cur.prev |
| 22 | + steps -= 1 |
| 23 | + return self.cur.val |
| 24 | + |
| 25 | + # O(n) |
| 26 | + def forward(self, steps: int) -> str: |
| 27 | + while self.cur.next and steps > 0: |
| 28 | + self.cur = self.cur.next |
| 29 | + steps -= 1 |
| 30 | + return self.cur.val |
| 31 | + |
| 32 | + |
| 33 | +# Array Implementation |
| 34 | +class BrowserHistory: |
| 35 | + def __init__(self, homepage: str): |
| 36 | + self.i = 0 |
| 37 | + self.len = 1 |
| 38 | + self.history = [homepage] |
| 39 | + |
| 40 | + # O(1) |
| 41 | + def visit(self, url: str) -> None: |
| 42 | + if len(self.history) < self.i + 2: |
| 43 | + self.history.append(url) |
| 44 | + else: |
| 45 | + self.history[self.i + 1] = url |
| 46 | + self.i += 1 |
| 47 | + self.len = self.i + 1 |
| 48 | + |
| 49 | + # O(1) |
| 50 | + def back(self, steps: int) -> str: |
| 51 | + self.i = max(self.i - steps, 0) |
| 52 | + return self.history[self.i] |
| 53 | + |
| 54 | + # O(1) |
| 55 | + def forward(self, steps: int) -> str: |
| 56 | + self.i = min(self.i + steps, self.len - 1) |
| 57 | + return self.history[self.i] |
0 commit comments