-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamz_Implement_StackAPI_Using_Heap.py
64 lines (54 loc) · 1.38 KB
/
amz_Implement_StackAPI_Using_Heap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#This problem was asked by Amazon.
#Implement a stack API using only a heap. A stack implements the following methods:
#push(item), which adds an element to the stack
#pop(), which removes and returns the most recently added element (or throws an error if there is nothing on the stack)
# Recall that a heap has the following operations:
#push(item), which adds a new key to the heap
# pop(), which removes and returns the max value of the heap
# Solution:
class Stack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, val):
self.stack.append(val)
if not self.max_stack or val > self.stack[self.max_stack[-1]]:
self.max_stack.append(len(self.stack) - 1)
def pop(self):
if not self.stack:
return None
if len(self.stack) - 1 == self.max_stack[-1]:
self.max_stack.pop()
return self.stack.pop()
def max(self):
if not self.stack:
return None
return self.stack[self.max_stack[-1]]
s = Stack()
s.push(1)
s.push(3)
s.push(2)
s.push(5)
assert s.max() == 5
s.pop()
assert s.max() == 3
s.pop()
assert s.max() == 3
s.pop()
assert s.max() == 1
s.pop()
assert not s.max()
s = Stack()
s.push(10)
s.push(3)
s.push(2)
s.push(5)
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert not s.max()