Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 9bcc2fe

Browse files
committed
optimized min stack algorithm, for constant time min-search
1 parent 554af6d commit 9bcc2fe

File tree

1 file changed

+10
-24
lines changed

1 file changed

+10
-24
lines changed

solutions/155 - Min Stack.py

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import sys
2-
3-
4-
# implementation of queue data structure from scratch using list
1+
# implementation of stack data structure from scratch using linkedlist
2+
# many solutions I seen use a regular [] list with built in pop(), append() methods
53
class Node:
64
def __init__(self, data=None, next=None):
75
self.data = data
@@ -11,25 +9,22 @@ def __init__(self, data=None, next=None):
119
class MinStack:
1210
def __init__(self):
1311
self.head = None
14-
15-
def __repr__(self):
16-
# traverse stack and print all values
17-
curr = self.head
18-
nodes_list = []
19-
while curr:
20-
nodes_list.append(str(curr.data))
21-
curr = curr.next
22-
nodes_list.append('None')
23-
return ', '.join(nodes_list)
12+
self.smallest = [9223372036854775807]
2413

2514
def pop(self):
2615
# remove node from head
2716
current = self.head
17+
if current.data == self.smallest[-1]:
18+
self.smallest.pop()
2819
self.head = current.next
2920
current = None
3021

3122
def push(self, x):
3223
# insert new node between head and first element in the list
24+
# keep track of the smallest number being pushed into the list
25+
if x <= self.smallest[-1]:
26+
self.smallest.append(x)
27+
3328
new_node = Node(data=x) # initialize new node
3429
new_node.next = self.head
3530
self.head = new_node
@@ -42,13 +37,4 @@ def top(self):
4237
return top
4338

4439
def getMin(self):
45-
if self.head is None:
46-
return None
47-
48-
minimum = sys.maxsize
49-
current = self.head
50-
while current is not None:
51-
if minimum > current.data:
52-
minimum = current.data
53-
current = current.next
54-
return minimum
40+
return self.smallest[-1]

0 commit comments

Comments
 (0)