![]() |
VOOZH | about |
We have an empty stack and can perform push and pop operations. We are given two arrays, a[] and b[] of same length, where a[] represents the order in which elements are pushed onto the stack, and b[] represents the order in which elements are popped from the stack. Find whether the given push and pop sequences are valid.
Examples:
Input: a[] = [1, 2, 3], b[] = [2, 1, 3]
Output: true
Explanation: Push 1 and 2. Since b[] requires 2 first, pop 2, then pop 1 next. Finally, push 3 and pop it. The push and pop sequence matches a[] and b[].Input: a[] = [1, 2, 3], b[] = [3, 1, 2]
Output: false
Explanation: After pushing 1, 2, and 3, we can pop 3 as required. But the next element in b[] is 1, while the stack top is 2. Since 1 is blocked under 2, this order cannot be achieved.
Table of Content
The idea is to simulate the stack operations while keeping track of the remaining elements to process using queues.
We push elements from a[] in order, and for each element, we check if it matches the front of b[] (the expected pop order). If it matches, we remove it from b[]; if not, we push it onto a stack. After each push, we also check the top of the stack if it matches the front of b[], we pop from the stack and remove it from b[]. By repeating this, we see if all elements in b[] can be matched. If yes, the pop sequence is valid; otherwise, it is not.
true
In this approach, we donβt actually build queues or modify the input arrays. Instead, we directly simulate the push and pop operations on a stack.
Each element from a[] is pushed onto the stack one by one. After every push, we check whether the top of the stack matches the current element of b[]. If it does, we pop it from the stack and move forward in b[]. This process repeats until all elements of a[] have been pushed and checked. If by the end all elements of b[] have been successfully matched and popped, the permutation is valid (returns true); otherwise, it is invalid (returns false).
true