Skip to content

Commit 9ece1b7

Browse files
Add Py solution to LC946
1 parent 6fb18c5 commit 9ece1b7

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

LC946-Validate-Stack-Sequences.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
Given two sequences pushed and popped with distinct values, return true if
3+
and only if this could have been the result of a sequence of push and pop
4+
operations on an initially empty stack.
5+
6+
7+
Example 1:
8+
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
9+
Output: true
10+
Explanation: We might do the following sequence:
11+
push(1), push(2), push(3), push(4), pop() -> 4,
12+
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
13+
14+
Example 2:
15+
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
16+
Output: false
17+
Explanation: 1 cannot be popped before 2.
18+
19+
20+
Constraints:
21+
(*) 0 <= pushed.length == popped.length <= 1000
22+
(*) 0 <= pushed[i], popped[i] < 1000
23+
(*) pushed is a permutation of popped.
24+
(*) pushed and popped have distinct values.
25+
"""
26+
from typing import List
27+
28+
29+
class Solution:
30+
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
31+
"""
32+
Runtime complexity: O(n)
33+
Space complexity: O(n)
34+
"""
35+
i_popped = 0
36+
i_pushed = 0
37+
stack = list()
38+
while i_pushed < len(pushed):
39+
# we may keep pushing
40+
# check if popping is possible
41+
if stack and i_popped < len(popped) and stack[-1] == popped[i_popped]:
42+
stack.pop()
43+
i_popped += 1
44+
else:
45+
stack.append(pushed[i_pushed])
46+
i_pushed += 1
47+
48+
while i_popped < len(popped):
49+
if not stack or stack[-1] != popped[i_popped]:
50+
return False
51+
52+
stack.pop()
53+
i_popped += 1
54+
return True
55+
56+
57+
if __name__ == '__main__':
58+
from run_tests import run_tests
59+
60+
correct_answers = [
61+
[[1,2,3,4,5], [4,5,3,2,1], True],
62+
[[1,2,3,4,5], [4,3,5,1,2], False],
63+
[[1,2,3,4,5], [4,3,5,2,1], True],
64+
[[1,2,3,4,5], [4,5,3,1,2], False]
65+
]
66+
methods = ['validateStackSequences', ]
67+
for method in methods:
68+
print(f'Running tests for {method}')
69+
run_tests(getattr(Solution(), method), correct_answers)

0 commit comments

Comments
 (0)