LeetCode Video
LeetCode Video
AboutContactPrivacyTerms
© 2024 LeetCode Video. All rights reserved.
Your browser does not support the video tag.

946. Validate Stack Sequences

29 views
Medium
queue

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.

946. Validate Stack Sequences

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.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] Output: false Explanation: 1 cannot be popped before 2.

Constraints:

1 <= pushed.length <= 1000 0 <= pushed[i] <= 1000 All the elements of pushed are unique. popped.length == pushed.length popped is a permutation of pushed.

Solutions

cpp
class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> s;
        int j = 0;  // index for popped array
        
        for (int x : pushed) {
            s.push(x);
            // Check if current stack top matches the element to be popped
            while (!s.empty() && j < popped.size() && s.top() == popped[j]) {
                s.pop();
                j++;
            }
        }
        
        return s.empty();  // If stack is empty, all elements were successfully matched
    }
};
java
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int j = 0;  // index for popped array
        
        for (int x : pushed) {
            stack.push(x);
            // While stack is not empty and top element matches current element to pop
            while (!stack.isEmpty() && j < popped.length && stack.peek() == popped[j]) {
                stack.pop();
                j++;
            }
        }
        
        return stack.isEmpty();  // If stack is empty, sequence is valid
    }
}
python3
def validateStackSequences(pushed, popped):
    stack = []
    j = 0  # index for popped array
    
    for x in pushed:
        stack.append(x)
        # While stack is not empty and top element matches current element to pop
        while stack and j < len(popped) and stack[-1] == popped[j]:
            stack.pop()
            j += 1
    
    return len(stack) == 0  # If stack is empty, sequence is valid
python
def validateStackSequences(pushed, popped):
    stack = []
    j = 0  # index for popped array
    
    for x in pushed:
        stack.append(x)
        # While stack is not empty and top element matches current element to pop
        while stack and j < len(popped) and stack[-1] == popped[j]:
            stack.pop()
            j += 1
    
    return len(stack) == 0  # If stack is empty, sequence is valid
javascript
function validateStackSequences(pushed, popped) {
    const stack = [];
    let j = 0;  // index for popped array
    
    for (const x of pushed) {
        stack.push(x);
        // While stack is not empty and top element matches current element to pop
        while (stack.length > 0 && j < popped.length && stack[stack.length - 1] === popped[j]) {
            stack.pop();
            j++;
        }
    }
    
    return stack.length === 0;  // If stack is empty, sequence is valid
}
typescript
function validateStackSequences(pushed: number[], popped: number[]): boolean {
    const stack: number[] = [];
    let j: number = 0;  // index for popped array
    
    for (const x of pushed) {
        stack.push(x);
        // While stack is not empty and top element matches current element to pop
        while (stack.length > 0 && j < popped.length && stack[stack.length - 1] === popped[j]) {
            stack.pop();
            j++;
        }
    }
    
    return stack.length === 0;  // If stack is empty, sequence is valid
}
c
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize) {
    int stack[1000];  // Maximum stack size is 1000
    int top = -1;     // Stack top pointer
    int j = 0;        // Index for popped array
    
    for (int i = 0; i < pushedSize; i++) {
        stack[++top] = pushed[i];  // Push to stack
        
        // Check if current stack top matches the element to be popped
        while (top >= 0 && j < poppedSize && stack[top] == popped[j]) {
            top--;  // Pop from stack
            j++;
        }
    }
    
    return top == -1;  // If stack is empty, sequence is valid
}
go
func validateStackSequences(pushed []int, popped []int) bool {
    var stack []int
    j := 0  // index for popped array
    
    for _, x := range pushed {
        stack = append(stack, x)
        // While stack is not empty and top element matches current element to pop
        for len(stack) > 0 && j < len(popped) && stack[len(stack)-1] == popped[j] {
            stack = stack[:len(stack)-1]  // pop
            j++
        }
    }
    
    return len(stack) == 0  // If stack is empty, sequence is valid
}
swift
func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
    var stack = [Int]()
    var j = 0  // index for popped array
    
    for x in pushed {
        stack.append(x)
        // While stack is not empty and top element matches current element to pop
        while !stack.isEmpty && j < popped.count && stack.last! == popped[j] {
            stack.removeLast()
            j += 1
        }
    }
    
    return stack.isEmpty  // If stack is empty, sequence is valid
}
ruby
def validate_stack_sequences(pushed, popped)
    stack = []
    j = 0  # index for popped array
    
    pushed.each do |x|
        stack.push(x)
        # While stack is not empty and top element matches current element to pop
        while !stack.empty? && j < popped.length && stack.last == popped[j]
            stack.pop
            j += 1
        end
    end
    
    stack.empty?  # If stack is empty, sequence is valid
end
php
function validateStackSequences($pushed, $popped) {
    $stack = [];
    $j = 0;  // index for popped array
    
    foreach ($pushed as $x) {
        array_push($stack, $x);
        // While stack is not empty and top element matches current element to pop
        while (!empty($stack) && $j < count($popped) && end($stack) === $popped[$j]) {
            array_pop($stack);
            $j++;
        }
    }
    
    return empty($stack);  // If stack is empty, sequence is valid
}
scala
object Solution {
    def validateStackSequences(pushed: Array[Int], popped: Array[Int]): Boolean = {
        var stack = List[Int]()
        var j = 0  // index for popped array
        
        for (x <- pushed) {
            stack = x :: stack  // push
            // While stack is not empty and top element matches current element to pop
            while (stack.nonEmpty && j < popped.length && stack.head == popped(j)) {
                stack = stack.tail  // pop
                j += 1
            }
        }
        
        stack.isEmpty  // If stack is empty, sequence is valid
    }
}

Related Problems

More related problems will appear here.