Verify Preorder Sequence in Binary Search Tree — LeetCode 255 Python Solution

MediumLeetCode PremiumStackTreeBinary Search TreeRecursionArrayBinary TreeMonotonic Stack
Problem
#255
Pattern
Stack
Reading time
2 min

The problem

Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.

Example

Input
preorder = [5,2,1,3,6]
Output
true

Python solution

Python
class Solution:
    def verifyPreorder(self, preorder: List[int]) -> bool:
        stk = []
        last = -inf
        for x in preorder:
            if x < last:
                return False
            while stk and stk[-1] < x:
                last = stk.pop()
            stk.append(x)
        return True

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 255. Verify Preorder Sequence in Binary Search Tree is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 255. Verify Preorder Sequence in Binary Search Tree?
LeetCode 255. Verify Preorder Sequence in Binary Search Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 255. Verify Preorder Sequence in Binary Search Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 255. Verify Preorder Sequence in Binary Search Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 255. Verify Preorder Sequence in Binary Search Tree cover?
LeetCode 255. Verify Preorder Sequence in Binary Search Tree is tagged Stack, Tree, Binary Search Tree, Recursion, Array, Binary Tree and Monotonic Stack on LeetCode.
Is LeetCode 255. Verify Preorder Sequence in Binary Search Tree a premium problem?
Yes. LeetCode 255. Verify Preorder Sequence in Binary Search Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview