Verify Preorder Sequence in Binary Search Tree - Problem

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

In a binary search tree, for any node:

  • All values in the left subtree are less than the node's value
  • All values in the right subtree are greater than the node's value

In a preorder traversal, we visit nodes in the order: root → left subtree → right subtree

Input & Output

Example 1 — Valid BST Preorder
$ Input: preorder = [5,2,1,3,6]
Output: true
💡 Note: This represents a valid BST: root=5, left subtree has 2,1,3 (all < 5), right subtree has 6 (> 5). The preorder traversal follows root→left→right pattern.
Example 2 — Invalid BST Preorder
$ Input: preorder = [5,2,6,1,3]
Output: false
💡 Note: After visiting 6 (right subtree of 5), we cannot visit 1 which is less than 5. This violates BST property as we're in the right subtree where all values should be > 5.
Example 3 — Single Node
$ Input: preorder = [1]
Output: true
💡 Note: A single node is always a valid BST, so any single element array is a valid preorder sequence.

Constraints

  • 1 ≤ preorder.length ≤ 104
  • 1 ≤ preorder[i] ≤ 108
  • All integers in preorder are unique

Visualization

Tap to expand
Verify Preorder Sequence: Is [5,2,1,3,6] a valid BST?Input Array:52136Resulting BST:52613✓ Valid BST Preorder SequenceLeft subtree values < 5, Right subtree values > 5
Understanding the Visualization
1
Input
Preorder array [5,2,1,3,6]
2
Process
Use stack to track path and validate BST property
3
Output
Return true if valid BST preorder sequence
Key Takeaway
🎯 Key Insight: Use a monotonic stack to efficiently validate BST constraints during preorder traversal
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 12
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen