Leetcode 946: Validate Stack Sequences

grid47
grid47
Exploring patterns and algorithms
Aug 4, 2024 6 min read

You are given two integer arrays, pushed and popped, each containing distinct values. The arrays represent the order of elements being pushed onto and popped from an initially empty stack. Your task is to determine if it is possible to obtain the popped sequence from the pushed sequence through a series of valid stack push and pop operations.
Problem
Approach
Steps
Complexity
Input: The input consists of two integer arrays: `pushed` and `popped`. Both arrays contain distinct values, and the length of both arrays is the same.
Example: Input: pushed = [1, 2, 3, 4, 5], popped = [5, 4, 3, 2, 1]
Constraints:
• 1 <= pushed.length <= 1000
• 0 <= pushed[i] <= 1000
• All elements in pushed and popped are unique.
• popped.length == pushed.length
• popped is a permutation of pushed.
Output: Return true if the sequence `popped` can be obtained by performing a sequence of push and pop operations on an initially empty stack, otherwise return false.
Example: Output: true
Constraints:
• The input arrays are always valid, and the answer will fit in a boolean value.
Goal: The goal is to verify if the `popped` array can be formed by performing valid stack operations on the `pushed` array.
Steps:
• 1. Initialize an empty stack to simulate the stack operations.
• 2. Use two pointers, one for traversing `pushed` and another for traversing `popped`.
• 3. For each element in `pushed`, push it onto the stack.
• 4. While the stack is not empty and the top of the stack matches the current element in `popped`, pop the top element from the stack and move the pointer in `popped`.
• 5. Repeat the process until all elements from `pushed` are processed and the stack is empty.
Goal: The problem constraints ensure the solution handles arrays with distinct values and valid stack operations.
Steps:
• The length of the arrays is between 1 and 1000.
• The values in `pushed` and `popped` are distinct and within the range of 0 to 1000.
Assumptions:
• The arrays `pushed` and `popped` contain only unique values.
• The arrays are permutations of each other, meaning that `popped` can be re-arranged into `pushed`.
Input: Input: pushed = [1, 2, 3, 4, 5], popped = [5, 4, 3, 2, 1]
Explanation: In this example, we can simulate the stack operations as follows: push(1), push(2), push(3), push(4), push(5), then pop elements in reverse order: pop() -> 5, pop() -> 4, pop() -> 3, pop() -> 2, pop() -> 1. Since the stack operations produce the same order as `popped`, the output is true.

Input: Input: pushed = [1, 2, 3, 4, 5], popped = [5, 3, 4, 1, 2]
Explanation: In this example, the element 1 cannot be popped before 2. It is not possible to obtain the sequence `popped` by performing valid stack operations on `pushed`, so the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus