Check preorder is valid or not

Pattern: Validate BST

medium

Simulate building the BST from the preorder with a stack. When a value is bigger than the stack top, we are moving into a right subtree: pop the smaller values, and the last one popped becomes a lower limit that no later value may go below.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given an array of distinct values, return whether it can be the preorder traversal of some BST. [2, 4, 3] is true; [2, 4, 1] is false. The catalogue has no practice link for this one.

Think first

  • After you move into the right subtree of a node, what must every later value be?
  • How do you know you moved right?
  • Which value becomes the new lower limit?

Hints

    Brute force, and why it fails

    Build the BST from the preorder and compare its preorder with the input: O(n h).

    The key insight

    The stack holds the path of nodes whose right side is still open, and the popped values are exactly the lower limits.

    Dry run

    low30
    stack40 35

    pre = [40, 30, 35, 80, 100]. Push 40, 30. 35 > 30: pop 30, low = 30. Push 35.

    Step 1 of 3

    The plan

    low = -inf; stack = []
    for v: if v < low: false
      while stack and top < v: low = pop
      push v
    return true
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each value is pushed and popped once.

    Edge cases

    • One value: true.
    • Increasing values: true.
    • Decreasing values: true.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean canRepresentBST(int[] pre) {
            Deque<Integer> st = new ArrayDeque<>();
            int low = Integer.MIN_VALUE;            // after turning right past a value, nothing may go below it
            for (int v : pre) {
                if (v < low) return false;
                while (!st.isEmpty() && st.peek() < v) low = st.pop();   // v is in the right subtree of these
                st.push(v);
            }
            return true;
        }
    }

    C++

    class Solution {
    public:
        bool canRepresentBST(vector<int>& pre) {
            stack<int> st;
            int low = INT_MIN;                      // after turning right past a value, nothing may go below it
            for (int v : pre) {
                if (v < low) return false;
                while (!st.empty() && st.top() < v) { low = st.top(); st.pop(); }   // v is in the right subtree of these
                st.push(v);
            }
            return true;
        }
    };

    Python

    class Solution:
        def canRepresentBST(self, pre: list[int]) -> bool:
            st, low = [], float("-inf")             # after turning right past a value, nothing may go below it
            for v in pre:
                if v < low:
                    return False
                while st and st[-1] < v:
                    low = st.pop()                  # v is in the right subtree of these
                st.append(v)
            return True

    Common mistakes

    • Checking only neighbouring values.
    • Forgetting to update the lower limit.

    Similar problems