Skip to content

Commit edfa088

Browse files
authored
Add files via upload
1 parent 3582b3f commit edfa088

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
946. Validate Stack Sequences(Medium)
2+
3+
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
4+
5+
6+
7+
Example 1:
8+
9+
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
10+
Output: true
11+
Explanation: We might do the following sequence:
12+
push(1), push(2), push(3), push(4),
13+
pop() -> 4,
14+
push(5),
15+
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
16+
Example 2:
17+
18+
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
19+
Output: false
20+
Explanation: 1 cannot be popped before 2.
21+
22+
23+
Constraints:
24+
25+
1 <= pushed.length <= 1000
26+
0 <= pushed[i] <= 1000
27+
All the elements of pushed are unique.
28+
popped.length == pushed.length
29+
popped is a permutation of pushed.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
3+
stack = []
4+
i = 0 # popped's index
5+
6+
for x in pushed:
7+
stack.append(x)
8+
while stack and stack[-1] == popped[i]:
9+
stack.pop()
10+
i += 1
11+
12+
return not stack

0 commit comments

Comments
 (0)