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 in Binary Search Tree INPUT preorder = [5, 2, 1, 3, 6] 5 2 1 3 6 0 1 2 3 4 Expected BST Structure: 5 2 1 3 6 left < 5 right > 5 ALGORITHM STEPS 1 Use Stack + Lower Bound Init: stack=[], low=-inf 2 Process Each Element If val < low: return false 3 Pop When val > stack.top Update low = popped value 4 Push Current Value Continue to next element Execution Trace: val stack low action 5 [5] -inf push 5 2 [5,2] -inf push 2 1 [5,2,1] -inf push 1 3 [5,3] 2 pop 1,2; push 3 6 [6] 5 pop 3,5; push 6 Time: O(n) | Space: O(n) No violations found! FINAL RESULT Valid Preorder Sequence true Output: true Verification: [OK] No value violated lower bound [OK] Stack ops completed normally [OK] All elements processed BST property maintained: Left subtree < root < Right subtree {1,2,3} < 5 < {6} Key Insight: In valid BST preorder, when we see a value greater than stack top, we're moving to a right subtree. All popped values become the new lower bound - no future value can be less than them. This simulates the BST property: once we go right, we can never see smaller values from the left subtree. TutorialsPoint - Verify Preorder Sequence in Binary Search Tree | Optimal Stack-based Solution
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