Skip to content

Validate Stack Sequences

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

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.

pushed = [1, 2, 3, 4, 5], popped = [4, 5, 3, 2, 1]  →  true
  push 1, 2, 3, 4, pop 4, push 5, pop 5, pop 3, pop 2, pop 1
 
pushed = [1, 2, 3, 4, 5], popped = [4, 3, 5, 1, 2]  →  false
  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.