[Naive approach] By find next element - O(n^2) Time and O(n) Space
The idea is to search for next greater element for every pre[i] starting from first one. Here below steps that can be follow for this approach:
Find the first greater value on right side of current node. Let the index of this node be j.
Return true if following conditions hold. Else return false.
All values after the above found greater value are greater than current node.
Recursive calls for the subarrays pre[i+1..j-1] and pre[j+1..n-1] also return true.
The Time complexity for this approach is O(n ^ 2) where n is the number of elements in pre order.
[Expected Approach - 1] Using Stack - O(n) Time and O(n) Space
The idea is to use a stack. This problem is similar to Next (or closest) Greater Element problem. Here we find the next greater element and after finding next greater, if we find a smaller element, then return false.
Follow the steps below to solve the problem:
Start with the smallest possible value as the root and an empty stack.
Iterate through the array. If the current element is smaller than the root, return false (violates the BST property).
For each element:
If it is smaller than the stack's top, it belongs to the left subtree. Push it onto the stack.
If it is larger, it belongs to the right subtree. Pop elements from the stack (moving up the tree) until the top is larger than the current element, updating the root with the last popped value. Push the current element onto the stack.
If the loop completes without violations, the array represents a valid BST preorder traversal.
Output
true
[Expected Approach - 2] Without Using Stack - O(n) Time and O(n) Space
We can check if the given preorder traversal is valid or not for a BST without using stack. The idea is to use the similar concept of Building a BST using narrowing bound algorithm. We will recursively visit all nodes, but we will not build the nodes. In the end, if the complete array is not traversed, then that means that array can not represent the preorder traversal of any binary tree.