Validate Stack Sequences

Medium · Stack & Strings · Array · Stack · Simulation

Problem

You are given two integer arrays pushed and popped, each holding the same distinct values. Starting from an empty stack, you push the values of pushed in order, and at any moment you may pop the top of the stack.

Return true if some interleaving of these pushes and pops removes the values in exactly the order given by popped, and false otherwise.

Examples

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

Push 1, push 2, pop 2, pop 1, push 3, push 4, pop 4, pop 3.

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

Once 3 is popped, 2 sits above 1, so 1 cannot come out next.

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

Push everything, then pop everything.

Constraints

Approaches

Follow-up

Because the values are distinct, the greedy simulation is not just one way but the only way: the pushes and pops are forced. The use cases return that forced sequence of operations, and the largest height the stack reaches.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…