[LeetCode] Validate Stack Sequences

946. Validate Stack Sequences

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int pol = 0, pul=0;
for(auto n : pushed) {
pushed[pul++] = n;
while(pul > 0 and pushed[pul-1] == popped[pol]) {
pol++;
pul--;
}
}
return pul == 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/validate-stack-sequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.