Skip to the code
cf.
+25 XP

#255 Replay a Stack Log

medium

A debugging tool recorded the order in which values were pushed onto a stack, pushed, and separately the order in which they were popped, popped. Pops can happen at any time between pushes. Every value is distinct, and every pushed value was popped exactly once.

Write canReplay(pushed, popped) that returns true if some way of mixing the pushes and pops produces exactly this pop order, and false otherwise.

Example 1

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

Push 1 to 4, pop 4, push 5, pop 5, then pop 3, 2, 1.

Example 2

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

After popping 4, 3, 5, the stack holds 1 under 2, so 1 can't come out before 2.

Constraints

  • 0 <= pushed.length <= 1000
  • popped has the same values as pushed, in some order.
  • All values are distinct.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).