Intermediate Level
Implement the validateStackPushPopSequence method that checks whether a pop sequence is valid for the given push sequence.
The input contains two integer arrays, pushed and popped, along with their length size. The pushed array shows the order in which values are pushed into a stack.
Your task is to check whether the popped array can be a valid pop order for that stack. A value can be popped only if it is currently on the top of the stack.
Simulate the stack operations.
Push values from the pushed array one by one. After every push, keep popping while the top of the stack matches the next value required by the popped array.
At the end, if all values from popped were matched, the sequence is valid. Otherwise, it is not possible with normal stack behavior.
Pseudocode:
function validateStackPushPopSequence(pushed, popped, size):
stack = empty stack
popIndex = 0
for i from 0 to size - 1:
push pushed[i] into stack
while stack is not empty and stack top == popped[popIndex]:
pop from stack
popIndex++
return popIndex == size