Skip to content

Commit d3ec626

Browse files
authored
Merge pull request neetcode-gh#1243 from hrishikeshtak/main
Create: 1472-Design-Browser-History.py
2 parents 215ed15 + ea95ee9 commit d3ec626

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
1472. Design Browser History
3+
"""
4+
5+
6+
class DLLNode:
7+
def __init__(self, val):
8+
self.val = val
9+
self.prev = None
10+
self.next = None
11+
12+
13+
class BrowserHistory:
14+
def __init__(self, homepage: str):
15+
# initialize head and tail to dummy node
16+
self.head = DLLNode(-1)
17+
self.tail = DLLNode(-1)
18+
19+
self.head.next = self.tail
20+
self.tail.prev = self.head
21+
22+
# insert homepage at head node
23+
self.insertAtHead(homepage)
24+
# update cur pointer to homepage
25+
self.cur = self.head.next
26+
27+
def insertAtHead(self, homepage: str):
28+
temp = DLLNode(homepage)
29+
temp.next = self.head.next
30+
temp.prev = self.head
31+
32+
self.tail.prev = temp
33+
self.head.next = temp
34+
35+
def visit(self, url: str) -> None:
36+
temp = DLLNode(url)
37+
# clears forward history
38+
temp.next = self.tail
39+
temp.prev = self.cur
40+
self.tail.prev = temp
41+
self.cur.next = temp
42+
# update cur pointer to URL
43+
self.cur = self.cur.next
44+
45+
def back(self, steps: int) -> str:
46+
i = 0
47+
while self.cur.prev != self.head and i < steps:
48+
self.cur = self.cur.prev
49+
i += 1
50+
return self.cur.val
51+
52+
def forward(self, steps: int) -> str:
53+
i = 0
54+
while self.cur.next != self.tail and i < steps:
55+
self.cur = self.cur.next
56+
i += 1
57+
return self.cur.val

0 commit comments

Comments
 (0)