Validate Stack Sequences

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.

30:00

Validate Stack Sequences
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"pushed":[1,2,3,4,5],"popped":[4,5,3,2,1]}
Output: true
Constraints:
  • 1≤pushed.length≤10001 \leq \text{pushed.length} \leq 1000

  • 0≤pushed[i]≤10000 \leq \text{pushed}[i] \leq 1000

  • All the elements of pushed are unique.

  • popped.length=pushed.length\text{popped.length} = \text{pushed.length}

  • popped is a permutation of pushed.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"pushed":[1,2,3,4,5],"popped":[4,5,3,2,1]}

pushed (next to push: index 0)

1

i

2

1

3

2

4

3

5

4

stack (top first)

empty

top == popped[j] ?

∅≠4

start

popped (matched 0 of 5)

4

j

5

1

3

2

2

3

1

4

Replay the operations on a real stack. Push values in the pushed order, and pop greedily whenever the top is the next value popped expects.

Variables
VariableValue
i0
j0
topnull
popped[j]4
stack[]
DepthFunction Call
Stack empty
0/16