Validate Stack Sequences solution explained

Validate Stack Sequences gives you the order in which distinct values are pushed onto a stack and a proposed order in which they are popped, and asks whether some mix of pushes and pops could produce exactly that pop order. Simulate it: push the values in order, and after each push, pop for as long as the top equals the next value you are supposed to remove. The sequence is valid if everything gets popped. It runs in O(n) time.

By Published 7 min read

Restating the problem

You start with an empty stack. You are given two lists of equal length containing the same distinct integers: pushed, the order in which values must be pushed, and popped, an order in which values are said to come off. You may pop at any moment the stack is not empty, but each push must take the next value from pushed. Return true if there is a sequence of pushes and pops that removes the values in exactly the order given by popped, and false otherwise.

pushed = [4, 8, 1, 6]
popped = [8, 6, 1, 4]  ->  true   push 4, push 8, pop 8, push 1, push 6, pop 6, pop 1, pop 4
popped = [1, 8, 4, 6]  ->  true   push 4, 8, 1, pop 1, pop 8, pop 4, push 6, pop 6
popped = [6, 4, 8, 1]  ->  false  after 6 comes off, 1 is on top, so 4 cannot be next
Inputs made up for this page

What it tests

It looks like a search problem, since at every step you can either push or pop. The insight interviewers want is that there is no real choice: when the top of the stack is the value you need next, popping it now is the only way it will ever come off in time. Saying why the greedy move is safe matters as much as the code.

Slow but sure: try both moves

A direct approach explores every possibility. At each state you know how many values have been pushed, how many popped, and what is on the stack. Try popping if the top matches the next required value, and try pushing if any values are left. If any path pops everything, the answer is true. With copying stacks around and branching at every step, this is exponential in the worst case, so it is only a reference for small tests.

def validate_stack_sequences_slow(pushed, popped):
    def search(i, j, stack):
        if j == len(popped):
            return True
        if stack and stack[-1] == popped[j] and search(i, j + 1, stack[:-1]):
            return True
        if i < len(pushed) and search(i + 1, j, stack + [pushed[i]]):
            return True
        return False

    return search(0, 0, [])
Python: depth-first search over both moves. Exponential; for testing only.

Why the greedy pop is always right

Suppose the top of the stack is x and x is the next value in popped. If you push something else instead, x gets buried, and it can only come off after that new value comes off. But the pop order says x comes next, before any value not yet popped. So delaying can only break things, never help. And if the top is not the value you need, popping is not allowed anyway, so the only move is to push. Each step therefore has exactly one sensible move, and a single simulation decides the answer.

def validate_stack_sequences(pushed, popped):
    stack, j = [], 0
    for value in pushed:
        stack.append(value)
        while stack and stack[-1] == popped[j]:
            stack.pop()
            j += 1
    return j == len(popped)
Python: push in order, pop while the top matches

Index j never runs past the end inside the loop: there are as many values in popped as in pushed, and the stack is non-empty only while some value has been pushed but not yet popped.

function validateStackSequences(pushed, popped) {
  let size = 0; // stack lives in pushed[0 .. size - 1]
  let j = 0;
  for (const value of pushed) {
    pushed[size++] = value;
    while (size > 0 && pushed[size - 1] === popped[j]) {
      size--;
      j++;
    }
  }
  return size === 0;
}
JavaScript: the front of the pushed array doubles as the stack

Writing into pushed is safe because size never exceeds the index of the value being read, so you only overwrite slots you have already read. The for...of loop still sees the original values, since each slot is read before it can be overwritten. It saves memory, but it changes the caller's array, so say so in an interview and copy the array if that matters.

Complexity

n values
ApproachTimeExtra space
Search over push and pop movesExponential in the worst caseO(n) per path, plus copies
Greedy simulation with a stackO(n): each value pushed and popped at most onceO(n)
Greedy, reusing the push arrayO(n)O(1), but mutates the input
n values. Scroll sideways on a small screen.

Inputs that catch bugs

  • Empty lists: true.
  • A single value: always true.
  • Pop order equal to push order: push and pop each value immediately.
  • Pop order equal to the reverse of push order: push everything, then pop everything.
  • A pop order that needs a value buried under the top, like [6, 4, 8, 1] above: false.

Common mistakes

  • Popping only once after each push instead of in a loop, which fails when several values come off in a row.
  • Checking popped[j] without first checking the stack is non-empty.
  • Comparing the full stack with a slice of popped, which turns a linear solution into a quadratic one.
  • Forgetting that values are distinct. With repeated values, the greedy argument no longer holds as stated, so ask before assuming.
  • Mutating the input in place without saying so.

Variations

  • Count the valid pop orders: for n distinct pushes, the count is the nth Catalan number, a good fact to mention if asked.
  • Produce the operations: record "push x" and "pop" as you simulate and return the list, or report the first pop that fails.
  • Queue instead of stack: the only valid pop order is the push order itself.
  • Build a target from a stream: push numbers 1, 2, 3 and so on and pop the extras to form a target list; the same simulation with a counter instead of an array.

How to explain it out loud

Fictional example

Turning a search into a simulation
Candidate
At first it looks like I have two choices at every step, push or pop, which would be a search.
Candidate
But if the top is the next value to pop and I push instead, that value is buried under something that must come off later than it. So whenever the top matches, I must pop. Otherwise I must push.
Interviewer
So how do you decide the answer?
Candidate
I just run that one sequence of moves. If every value gets popped, it is valid. Each value goes on and off once, so it is linear.

Also in this batch: Exclusive Time of Functions replays a call log on a stack, and Remove Duplicate Letters decides pops greedily with a lookahead table. Valid Parentheses is the simplest stack simulation of all.

Working on it with Natively

Greedy arguments are easy to state badly under time pressure. During a practice session on a Mac or Windows computer, Natively can read the two lists from a screenshot, suggest the push-then-pop-while-matching simulation, and transcribe how you justified it, so you can check afterwards whether the reason the greedy move is safe actually came across. The AI coding practice page has the details.

Questions people ask

How do you solve Validate Stack Sequences?

Push the values in the given order. After each push, pop while the top equals the next value in the pop order. The sequence is valid if every value was popped by the end.

Why is popping greedily correct?

If the top is the next value to pop and you push instead, it gets buried under a value that must come off later, so it can never be popped in time. Popping immediately is the only option that can work.

What is the time complexity of Validate Stack Sequences?

O(n), because each value is pushed once and popped at most once. Space is O(n) for the stack, or O(1) if you reuse the push array.

How many pop orders are valid for n pushed values?

For n distinct values pushed in a fixed order, the number of valid pop orders is the nth Catalan number.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP