Stack Bash - Master data structures and algorithms

Valid stack sequence

Medium
Given two integer arrays pushed and popped, each with distinct values, write a function that returns True if this could have been the result of a sequence of push and pop operations on an initially empty stack, or False otherwise.
For example, given the following inputs:
pushed = [1, 2, 3, 4, 5]
popped = [4, 5, 3, 2, 1]
Your function should return True. We can push 1, 2, 3, 4, then pop 4, push 5, then pop 5, 3, 2, 1.
Stack visualization showing push and pop operations
However, for pushed = [1, 2, 3, 4, 5] and popped = [4, 3, 5, 1, 2], the answer is False. After pushing 1, 2, 3, 4 and popping 4, 3, then pushing 5 and popping 5, we are left with 1 on top of 2 -- so we cannot pop 1 before 2.

Try it first

Solution

6 Essential Stacks & Queues Coding Interview Problems

Master Stacks & Queues by trying the coding challenges below.
  1. 1.Implement StackEasy
  2. 2.Implement QueueEasy
  3. 3.Valid stack sequenceMedium
  4. 4.Max StackMedium
  5. 5.Valid ParenthesesMedium
  6. 6.Simplify PathMedium