Ctrl K

Replaying Stack Pushes and Pops

Medium
A stack starts empty. Numbers are pushed onto it strictly in the order of the array pushes, and at any moment between those pushes you may pop numbers off the top. All numbers in pushes are distinct, and pops holds the same numbers in some order. Return True if the pushes and pops can be interleaved so that numbers come off the stack exactly in the order of pops, and False otherwise.
Example 1
pushes=[7, 3, 9, 1], pops=[3, 9, 1, 7] → True

Push 7 and 3, pop 3; push 9, pop 9; push 1, pop 1; pop 7.

Example 2
pushes=[7, 3, 9, 1], pops=[9, 7, 1, 3] → False

To pop 9 we must push 7, 3 and 9. After 9 is gone, 3 sits on top of 7, so 7 cannot come out before 3.

Example 3
pushes=[4], pops=[4] → True
Constraints
  • 1 ≤ len(pushes) ≤ 1000
  • 0 ≤ pushes[i] ≤ 1000
  • All numbers in pushes are distinct
  • pops is a permutation of pushes
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRobots Clashing on a Rail MediumA Stack From a Number Stream MediumQuiz Score Log EasyA Picky Line at the Counter EasyRobots Crashing on a Rail Hard
loading Python…
Input
pushes=[7, 3, 9, 1], pops=[3, 9, 1, 7]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 103 tests on the server, hidden ones included.