Stack Permutations (Check if an array is stack permutation of other)

Pattern: Implementation

easy

Simulate. Push a's values in order, and after each push pop for as long as the top equals the next value b needs. b is a stack permutation of a exactly when every value of b gets produced this way.

The problem

Values of array a are pushed onto a stack in order, and may be popped to the output at any time. Return whether the output can be exactly array b. a = [1, 2, 3], b = [2, 1, 3] is possible; b = [3, 1, 2] is not. The values are different from each other.

Think first

  • When must you pop?
  • Can waiting ever help when the top already equals what b needs next?
  • How do you know you failed?

Hints

    Brute force, and why it fails

    Try every sequence of pushes and pops: exponential.

    The key insight

    The greedy simulation is forced: popping a match immediately is never wrong, so one pass decides it.

    Dry run

    10j

    a = [1, 2, 3], b = [2, 1, 3]. Push 1: the top 1 is not b[0] = 2.

    Step 1 of 4

    The plan

    j = 0
    for v in a:
        push v
        while stack and j < len(b) and top == b[j]: pop; j += 1
    return j == len(b)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each value is pushed and popped at most once.

    Edge cases

    • b equal to a: pop right after each push.
    • b reversed: push everything, then pop everything.
    • One value.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean isStackPermutation(int[] a, int[] b) {
            Deque<Integer> st = new ArrayDeque<>();
            int j = 0;                              // the next value b expects
            for (int v : a) {
                st.push(v);                         // feed a into the stack in order
                while (!st.isEmpty() && j < b.length && st.peek() == b[j]) {
                    st.pop();                       // pop whenever the top is what b needs next
                    j++;
                }
            }
            return j == b.length;                   // b fully produced
        }
    }

    C++

    class Solution {
    public:
        bool isStackPermutation(vector<int>& a, vector<int>& b) {
            stack<int> st;
            size_t j = 0;                           // the next value b expects
            for (int v : a) {
                st.push(v);                         // feed a into the stack in order
                while (!st.empty() && j < b.size() && st.top() == b[j]) {
                    st.pop();                       // pop whenever the top is what b needs next
                    j++;
                }
            }
            return j == b.size();                   // b fully produced
        }
    };

    Python

    class Solution:
        def isStackPermutation(self, a: list[int], b: list[int]) -> bool:
            st, j = [], 0                           # j: the next value b expects
            for v in a:
                st.append(v)                        # feed a into the stack in order
                while st and j < len(b) and st[-1] == b[j]:
                    st.pop()                        # pop whenever the top is what b needs next
                    j += 1
            return j == len(b)                      # b fully produced

    Common mistakes

    • Popping only once per push instead of in a loop.
    • Comparing with b[j] after j has reached the end.

    Similar problems