Skip to content
Decoder

Validate Stack Sequences

Medium

Problem

You get two lists, pushed and popped, each holding the same distinct values. Starting from an empty stack, you must push the values in the order of pushed, and you may pop at any time. Return true if some sequence of pushes and pops could produce exactly the order `popped` for the popped values, otherwise false.

Example 1

Input
pushed = [1, 2, 3, 4, 5], popped = [4, 5, 3, 2, 1]
Output
true

Example 2

  push 1, 2, 3, 4, pop 4, push 5, pop 5, pop 3, pop 2, pop 1

Example 3

Input
pushed = [1, 2, 3, 4, 5], popped = [4, 3, 5, 1, 2]
Output
false

Example 4

  1 is stuck under 2, so it cannot be popped before 2

Constraints

  • 1 <= pushed.length <= 1000
  • 0 <= pushed[i] <= 1000
  • All values in pushed are unique.
  • popped is a rearrangement of pushed.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.