Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #255: Verify Preorder Sequence in Binary Search Tree

In this guide, we solve Leetcode #255 Verify Preorder Sequence in Binary Search Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree. Example 1: Input: preorder = [5,2,1,3,6] Output: true Example 2: Input: preorder = [5,2,6,1,3] Output: false Constraints: 1 <= preorder.length <= 104 1 <= preorder[i] <= 104 All the elements of preorder are unique.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Stack, Tree, Binary Search Tree, Recursion, Array, Binary Tree, Monotonic Stack

Intuition

We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.

Each element is pushed and popped at most once, yielding a linear-time scan.

Approach

Maintain a stack that is either increasing or decreasing, depending on the query.

When the invariant is broken, pop and resolve answers for those indices.

Steps:

  • Scan elements once.
  • Pop while the monotonic condition is violated.
  • Use stack indices to update answers.

Example

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

Python Solution

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

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy