Validate Stack Sequences - Problem

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.

The arrays represent the order in which elements were pushed onto the stack and the order in which they were popped from the stack. Your task is to determine if the pop sequence is valid given the push sequence.

Key Points:

  • Stack follows LIFO (Last In, First Out) principle
  • All values in both arrays are distinct
  • Both arrays have the same length

Input & Output

Example 1 — Valid Sequence
$ Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
💡 Note: Push 1,2,3,4 → Pop 4 → Push 5 → Pop 5,3,2,1. This sequence is valid.
Example 2 — Invalid Sequence
$ Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
💡 Note: After popping 4,3, we need to pop 5, but 5 hasn't been pushed yet when 3 was on top.
Example 3 — Simple Case
$ Input: pushed = [1,2], popped = [2,1]
Output: true
💡 Note: Push 1,2 → Pop 2,1. Simple LIFO order works.

Constraints

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

Visualization

Tap to expand
Validate Stack Sequences INPUT pushed = [1,2,3,4,5] 1 2 3 4 5 popped = [4,5,3,2,1] 4 5 3 2 1 Stack (Initially Empty) [ ] ALGORITHM STEPS 1 Initialize Stack Create empty stack, j=0 2 Push Elements Push from pushed array 3 Pop When Match If top==popped[j], pop, j++ 4 Check Result Return stack.isEmpty() Simulation: Push Stack Pop 1,2,3,4 [1,2,3,4] 4 5 [1,2,3,5] 5 - [1,2,3] 3,2,1 - [ ] - FINAL RESULT true OK - Valid Final Stack State: EMPTY All elements pushed and popped successfully Pop sequence valid! [4,5,3,2,1] matches Key Insight: Simulate the stack operations: push elements one by one, and whenever the stack top matches the current popped element, pop it. If the stack is empty at the end, the sequence is valid. Time: O(n) | Space: O(n) - Each element is pushed and popped at most once. TutorialsPoint - Validate Stack Sequences | Optimal Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
125.0K Views
Medium Frequency
~15 min Avg. Time
3.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen