-
Notifications
You must be signed in to change notification settings - Fork 7
/
Min Max Stack Construction.py
68 lines (56 loc) · 1.86 KB
/
Min Max Stack Construction.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
65
66
67
68
"""
Min Max Stack Construction.py
Write a MinMaxStack class for a Min Max Stack. The class should support:
• Pushing and popping values on and off the stack.
• Peeking at the value at the top of the stack.
• Getting both the minimum and the maximum values in the stack at any given point in time.
All class methods, when considered independently, should run in constant time and with constant space.
Sample Usage
// All operations below are performed sequentially.
MinMaxStack(): - // instantiate a MinMaxStack
push(5): -
getMin(): 5
getMax(): 5
peek(): 5
push(7):
getMin(): 5
getMax(): 7
peek(): 7
push(2): -
getMin(): 2
getMax(): 7
peek(): 2
pop(): 2
pop(): 7
getMin(): 5
getMax(): 5
peek(): 5
"""
# SOLUTION 1
# Feel free to add new properties and methods to the class.
class MinMaxStack:
def __init__(self):
self.minMaxStack = []
self.stack = []
# O(1) time | O(1) space
def peek(self):
return self.stack[len(self.stack) - 1]
# O(1) time | O(1) space
def pop(self):
self.minMaxStack.pop()
return self.stack.pop()
# O(1) time | O(1) space
def push(self, number):
newMinMax = {'min': number, 'max': number}
if len(self.minMaxStack):
lastMinMax = self.minMaxStack[len(self.minMaxStack) - 1]
newMinMax['min'] = min(lastMinMax['min'], number)
newMinMax['max'] = max(lastMinMax['max'], number)
self.minMaxStack.append(newMinMax)
self.stack.append(number)
# O(1) time | O(1) space
def getMin(self):
return self.minMaxStack[len(self.minMaxStack) - 1]['min']
# O(1) time | O(1) space
def getMax(self):
return self.minMaxStack[len(self.minMaxStack) - 1]['max']