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.

Example 1
Inputpushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Outputtrue
This sequence is possible by pushing 1, 2, 3, and 4, popping 4, pushing 5, then popping 5, 3, 2, and 1.
Example 2
Inputpushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Outputfalse
1 cannot be popped before 2.

Constraints

  • 1 <= pushed.length <= 1000
  • 0 <= pushed[i] <= 1000
  • All the elements of pushed are unique.
  • popped.length == pushed.length
  • popped is a permutation of pushed.

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate