Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9065e70

Browse files
committed
Create: 0946-validate-stack-sequences.cpp
1 parent c440eb2 commit 9065e70

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

cpp/0946-validate-stack-sequences.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
Given two integer arrays pushed and popped each with distinct values,
3+
return true if this could have been the result of a sequence of push
4+
and pop operations on an initially empty stack, or false otherwise.
5+
6+
Time: O(n)
7+
Space: O(n)
8+
*/
9+
10+
class Solution {
11+
public:
12+
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
13+
stack<int> stk;
14+
int i = 0;
15+
for (int num : pushed) {
16+
stk.push(num);
17+
while (!stk.empty() && stk.top() == popped[i]) {
18+
stk.pop();
19+
++i;
20+
}
21+
}
22+
return stk.empty();
23+
}
24+
};
25+

0 commit comments

Comments
 (0)