Given an array representing the preorder traversal of a BST, determine whether it represents a skewed BST.

For example,

Input:  Preorder traversal of BST: [15, 30, 25, 18, 20]
 
Output: BST is skewed
 
Explanation: The Preorder traversal [15, 30, 25, 18, 20] represents the following skewed BST:

Skewed BST

Practice this problem

In a skewed BST, each node’s descendants are either smaller or larger than the node itself. This property holds for every node in the skewed BST. Therefore, in a preorder traversal of the skewed BST, each node’s descendants appear on the right, and all descendants must be either smaller or greater.

We can use the above property of skewed BST to solve this problem. The idea is to traverse the preorder sequence, and for each element, check if all values on the right are either smaller or larger. This can be easily done using two nested loops and in O(n2) time, where n is the size of the given sequence.

 
We can solve the problem in O(n) time by doing a single traversal of the array. The idea is to traverse the given preorder sequence from the end, keep track of the minimum and the maximum value found so far. Then for each encountered node, its value must be less than the minimum value so far or more than the maximum value found. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

BST is skewed

Java


Download  Run Code

Output:

BST is skewed

Python


Download  Run Code

Output:

BST is skewed

Alternatively, we can start from the beginning of the array and set the range for the elements to follow. Basically, we restrict each preorder descendant to the valid range for the given preorder traversal to represent a skewed BST. The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

BST is skewed

Java


Download  Run Code

Output:

BST is skewed

Python


Download  Run Code

Output:

BST is skewed

The time complexity of the above solutions is O(n) and doesn’t require any extra space.