Skip to content

Commit b4dc40f

Browse files
authored
Create design-a-stack-with-increment-operation.py
1 parent 4f82553 commit b4dc40f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Time: cotr: O(1)
2+
# push: O(1)
3+
# pop: O(1)
4+
# increment: O(1)
5+
# Space: O(n)
6+
7+
class CustomStack(object):
8+
9+
def __init__(self, maxSize):
10+
"""
11+
:type maxSize: int
12+
"""
13+
self.__max_size = maxSize
14+
self.__stk = []
15+
16+
def push(self, x):
17+
"""
18+
:type x: int
19+
:rtype: None
20+
"""
21+
if len(self.__stk) == self.__max_size:
22+
return
23+
self.__stk.append([x, 0])
24+
25+
def pop(self):
26+
"""
27+
:rtype: int
28+
"""
29+
if not self.__stk:
30+
return -1
31+
x, inc = self.__stk.pop()
32+
if self.__stk:
33+
self.__stk[-1][1] += inc
34+
return x + inc
35+
36+
def increment(self, k, val):
37+
"""
38+
:type k: int
39+
:type val: int
40+
:rtype: None
41+
"""
42+
i = min(len(self.__stk), k)-1
43+
if i >= 0:
44+
self.__stk[i][1] += val

0 commit comments

Comments
 (0)