AlgoInsight

DSA problem

Validate Stack Sequences

MediumStacksPattern: Stackstop600GoogleAmazonMicrosoftBloomberg

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.

In other words, we are asked: is there an interleaving of pushes (in the given push order) and pops such that the popped values come out exactly in the given pop order? Because every value is distinct, this is well-defined.

A brute-force search over all orderings is exponential. The clean greedy/simulation approach is to actually simulate a stack and decide, at each step, whether to push or to pop. The decisive observation is that whenever the top of our simulated stack matches the next expected pop, we MUST pop right now — if we waited and pushed more values on top, we'd never be able to surface the bottom value again.

The algorithm walks through pushed in order, pushing each value onto a simulated stack. After every push, repeatedly pop while the stack's top equals popped[j] (advancing j each time). At the end of the loop, if every popped value was matched (j == popped.length) the sequence is valid. Each value is pushed and popped at most once, so total work is O(n) time, O(n) space.

Examples

Example 1
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: Sequence: push 1, push 2, push 3, push 4, pop→4, push 5, pop→5, pop→3, pop→2, pop→1.
Example 2
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: After popping 4 and 3, the stack is [1,2,5] (top right). The next pop must be 5 or 2, but the sequence demands 5 then 1, which would leave 2 on top before 1 — impossible.
Example 3
Input: pushed = [1,0], popped = [1,0]
Output: true
Explanation: Push 1, pop→1, push 0, pop→0. Simple alternating pattern.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackarraysimulationgreedy

Browse all DSA problems