Check if an array can be Preorder of a BST

Last Updated : 20 Jun, 2026

Given an array arr[] consisting of distinct integers, check if the given array can represent preorder traversal of a BST.

Examples:

Input: arr[] = [40, 30, 35, 80, 100]
Output: true
Explanation: Given array can represent preorder traversal of below tree

Check-if-a-given-array-can-represent-Preorder-Traversal-of-Binary-Search-Tree


Input: arr[] = [2, 4, 3]
Output: true
Explanation: Given arr[] can represent preorder traversal of following BST:

blobid0_1780982743
Try It Yourself
redirect icon

[Naive approach] First Greater Element - O(n ^ 2) Time and O(n) Space

The idea is to treat the first element as the root, find the first greater element which separates the left and right subtrees, and verify that all elements in the right subtree are greater than the root. Recursively apply the same check to the left and right subarrays.

For example in [40, 30, 35, 80, 100], 40 is the first element, so we make it root. Now we look for the first element greater than 40, we find 80. So we know the structure of BST is as follows:

adassadasd
C++
#include <bits/stdc++.h>
using namespace std;

bool check(vector<int> &arr, int l, int r)
{

    // If subtree has 0 or 1 node
    if (l >= r)
        return true;

    int j = l + 1;

    // Find first element greater than root
    while (j <= r && arr[j] < arr[l])
        j++;

    // Check whether all elements in right subtree
    // are greater than root
    for (int k = j; k <= r; k++)
    {
        if (arr[k] < arr[l])
            return false;
    }

    // Recursively check left and right subtrees
    return check(arr, l + 1, j - 1) && check(arr, j, r);
}

bool canRepresentBST(vector<int> &arr)
{

    return check(arr, 0, arr.size() - 1);
}

// Driver Code
int main()
{

    vector<int> arr = {40, 30, 35, 80, 100};

    if (canRepresentBST(arr))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
Java
import java.util.*;

public class GFG {

    static boolean check(List<Integer> arr, int l, int r)
    {
        if (l >= r)
            return true;

        int j = l + 1;

        while (j <= r && arr.get(j) < arr.get(l))
            j++;

        for (int k = j; k <= r; k++) {
            if (arr.get(k) < arr.get(l))
                return false;
        }

        return check(arr, l + 1, j - 1) && check(arr, j, r);
    }

    static boolean canRepresentBST(List<Integer> arr)
    {
        return check(arr, 0, arr.size() - 1);
    }

    public static void main(String[] args)
    {
        List<Integer> arr
            = Arrays.asList(40, 30, 35, 80, 100);

        System.out.println(canRepresentBST(arr) ? "true"
                                                : "false");
    }
}
Python
def check(arr, l, r):
    # If subtree has 0 or 1 node
    if l >= r:
        return True

    j = l + 1

    # Find first element greater than root
    while j <= r and arr[j] < arr[l]:
        j += 1

    # Check whether all elements in right subtree
    # are greater than root
    for k in range(j, r + 1):
        if arr[k] < arr[l]:
            return False

    # Recursively check left and right subtrees
    return check(arr, l + 1, j - 1) and check(arr, j, r)


def canRepresentBST(arr):
    return check(arr, 0, len(arr) - 1)


# Driver Code
if __name__ == "__main__":

    arr = [40, 30, 35, 80, 100]

    if canRepresentBST(arr):
        print("true")
    else:
        print("false")
C#
using System;

public class GFG {
    static bool Check(int[] arr, int l, int r)
    {
        // If subtree has 0 or 1 node
        if (l >= r)
            return true;

        int j = l + 1;

        // Find first element greater than root
        while (j <= r && arr[j] < arr[l])
            j++;

        // Check whether all elements in right subtree
        // are greater than root
        for (int k = j; k <= r; k++) {
            if (arr[k] < arr[l])
                return false;
        }

        // Recursively check left and right subtrees
        return Check(arr, l + 1, j - 1) && Check(arr, j, r);
    }

    static bool CanRepresentBST(int[] arr)
    {
        return Check(arr, 0, arr.Length - 1);
    }

    // Driver Code
    static void Main()
    {
        int[] arr = { 40, 30, 35, 80, 100 };

        if (CanRepresentBST(arr))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function check(arr, l, r) {
    // If subtree has 0 or 1 node
    if (l >= r)
        return true;

    let j = l + 1;

    // Find first element greater than root
    while (j <= r && arr[j] < arr[l])
        j++;

    // Check whether all elements in right subtree
    // are greater than root
    for (let k = j; k <= r; k++) {
        if (arr[k] < arr[l])
            return false;
    }

    // Recursively check left and right subtrees
    return check(arr, l + 1, j - 1) && check(arr, j, r);
}

function canRepresentBST(arr) {
    return check(arr, 0, arr.length - 1);
}

// Driver Code
const arr = [40, 30, 35, 80, 100];

if (canRepresentBST(arr))
    console.log('true');
else
    console.log('false');

Output
true

[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.

Let us Understand with example:
Input: arr[] = [40, 30, 35, 80, 100]

  • Start with root = -∞ and an empty stack. Push 40 -> Stack = [40].
  • 30 is greater than root and smaller than stack top, so push it -> Stack = [40, 30].
  • 35 is greater than stack top 30, so pop 30 and update root = 30. Then push 35 -> Stack = [40, 35].
  • 80 is greater than stack top, so keep popping: 35 -> root = 35, 40 -> root = 40. Push 80 -> Stack = [80].
  • 100 is greater than 80, so pop 80 and update root = 80. Push 100. No element was found smaller than the current root, so the preorder traversal is valid and the answer is true.
C++
#include <bits/stdc++.h>
using namespace std;

bool canRepresentBST(vector<int> &arr)
{

    stack<int> s;

    // Initialize current root as minimum possible
    // value
    int root = INT_MIN;

    for (int i = 0; i < arr.size(); i++)
    {

        // If we find a node who is on right side
        // and smaller than root, return false
        if (arr[i] < root)
            return false;

        // If pre[i] is in right subtree of stack top,
        // Keep removing items smaller than pre[i]
        // and make the last removed item as new
        // root.
        while (!s.empty() && s.top() < arr[i])
        {
            root = s.top();
            s.pop();
        }

        // At this point either stack is empty or
        // pre[i] is smaller than root, push pre[i]
        s.push(arr[i]);
    }
    return true;
}

int main()
{
    vector<int> arr = {40, 30, 35, 80, 100};

    if (canRepresentBST(arr))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
Java
import java.util.*;

public class GFG {

    public static boolean canRepresentBST(List<Integer> arr)
    {

        Stack<Integer> s = new Stack<>();

        // Initialize current root as minimum possible
        // value
        int root = Integer.MIN_VALUE;

        for (int i = 0; i < arr.size(); i++) {

            // If we find a node who is on right side
            // and smaller than root, return false
            if (arr.get(i) < root)
                return false;

            // If arr[i] is in right subtree of stack top,
            // Keep removing items smaller than arr[i]
            // and make the last removed item as new
            // root.
            while (!s.isEmpty() && s.peek() < arr.get(i)) {
                root = s.pop();
            }

            // At this point either stack is empty or
            // arr[i] is smaller than root, push arr[i]
            s.push(arr.get(i));
        }
        return true;
    }

    public static void main(String[] args)
    {

        List<Integer> arr
            = Arrays.asList(40, 30, 35, 80, 100);

        if (canRepresentBST(arr))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
def canRepresentBST(arr):

    stack = []

    # Initialize current root as minimum possible
    # value
    root = float('-inf')

    for i in range(len(arr)):

        # If we find a node who is on right side
        # and smaller than root, return false
        if arr[i] < root:
            return False

        # If arr[i] is in right subtree of stack top,
        # Keep removing items smaller than arr[i]
        # and make the last removed item as new
        # root.
        while stack and stack[-1] < arr[i]:
            root = stack.pop()

        # At this point either stack is empty or
        # arr[i] is smaller than root, push arr[i]
        stack.append(arr[i])

    return True


# Driver Code
if __name__ == "__main__":

    arr = [40, 30, 35, 80, 100]

    if canRepresentBST(arr):
        print("true")
    else:
        print("false")
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static bool canRepresentBST(List<int> arr)
    {

        Stack<int> s = new Stack<int>();

        // Initialize current root as minimum possible
        // value
        int root = int.MinValue;

        for (int i = 0; i < arr.Count; i++) {

            // If we find a node who is on right side
            // and smaller than root, return false
            if (arr[i] < root)
                return false;

            // If arr[i] is in right subtree of stack top,
            // Keep removing items smaller than arr[i]
            // and make the last removed item as new
            // root.
            while (s.Count > 0 && s.Peek() < arr[i]) {
                root = s.Pop();
            }

            // At this point either stack is empty or
            // arr[i] is smaller than root, push arr[i]
            s.Push(arr[i]);
        }

        return true;
    }

    public static void Main()
    {

        List<int> arr
            = new List<int>{ 40, 30, 35, 80, 100 };

        if (canRepresentBST(arr))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function canRepresentBST(arr) {
    let s = [];
    let root = Number.NEGATIVE_INFINITY;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < root)
            return false;
        while (s.length > 0 && s[s.length - 1] < arr[i]) {
            root = s.pop();
        }
        s.push(arr[i]);
    }
    return true;
}

let arr = [40, 30, 35, 80, 100];
if (canRepresentBST(arr))
    console.log("true");
else
    console.log("false");

Output
true

[Expected Approach - 2] Pass Range in Recursion - O(n) Time and O(n) Space

The trick is to set a range {min .. max} for every node. We initialize range as [-inf, +inf]. We begin with the first element of the preorder traversal, Now moving forward, we set the range as [-inf, key] for left subtree and [key, inf] for right subtree. We mainly maintain a shared variable in function calls preIndex and increment it if we find the node in range. If reach end, then the tree is BST.

Follow the below steps to solve the problem:

  • Initialize the range as {-inf , +inf}
  • The first node will definitely be in range, so create a root node. 
  • To process the left subtree, set the range as {-inf, root.key} and for right subtree as [root.key, +inf]


Let us Understand with example:
Input: arr[] = [40, 30, 35, 80, 100]

  • Start with range (-∞, +∞). 40 lies in the range, so process it as the root and move to the next element.
  • For the left subtree of 40, range becomes (-∞, 40). 30 and then 35 fit within valid ranges and are processed.
  • After the left subtree is completed, move to the right subtree of 40 with range (40, +∞).
  • 80 and then 100 satisfy their respective valid ranges and are processed.
  • All elements are consumed (preIndex == n), so the array represents a valid BST preorder traversal.
C++
#include <bits/stdc++.h>
using namespace std;

void buildBSThelper(int &preIndex, int n, vector<int> &pre, int min, int max)
{

    // If we have processed all elements, return
    if (preIndex >= n)
        return;

    // If the current element lies between min and max,
    // it can be part of the BST
    if (min <= pre[preIndex] && pre[preIndex] <= max)
    {

        // Treat the current element as the root of
        // this subtree
        int rootData = pre[preIndex];
        preIndex++;

        buildBSThelper(preIndex, n, pre, min, rootData);
        buildBSThelper(preIndex, n, pre, rootData, max);
    }
}

bool canRepresentBST(vector<int> &arr)
{

    // Set the initial min and max values
    int min = INT_MIN, max = INT_MAX;

    // Start from the first element in
    // the array
    int preIndex = 0;
    int n = arr.size();

    buildBSThelper(preIndex, n, arr, min, max);

    // If all elements are processed, it means the
    // array represents a valid BST
    return preIndex == n;
}

// Driver Code
int main()
{

    vector<int> arr = {40, 30, 35, 80, 100};
    if (canRepresentBST(arr))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
Java
import java.util.*;

public class GFG {

    static void buildBSThelper(int[] preIndex, int n,
                               List<Integer> pre, int min,
                               int max)
    {

        // If we have processed all elements, return
        if (preIndex[0] >= n)
            return;

        // If the current element lies between min and max,
        // it can be part of the BST
        if (min <= pre.get(preIndex[0])
            && pre.get(preIndex[0]) <= max) {

            // Treat the current element as the root of
            // this subtree
            int rootData = pre.get(preIndex[0]);
            preIndex[0]++;

            buildBSThelper(preIndex, n, pre, min, rootData);
            buildBSThelper(preIndex, n, pre, rootData, max);
        }
    }

    static boolean canRepresentBST(List<Integer> arr)
    {

        // Set the initial min and max values
        int min = Integer.MIN_VALUE;
        int max = Integer.MAX_VALUE;

        // Start from the first element in
        // the array
        int[] preIndex = { 0 };
        int n = arr.size();

        buildBSThelper(preIndex, n, arr, min, max);

        // If all elements are processed, it means the
        // array represents a valid BST
        return preIndex[0] == n;
    }

    // Driver Code
    public static void main(String[] args)
    {

        List<Integer> arr
            = Arrays.asList(40, 30, 35, 80, 100);

        if (canRepresentBST(arr))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
def buildBSThelper(preIndex, n, pre, minVal, maxVal):

    # If we have processed all elements, return
    if preIndex[0] >= n:
        return

    # If the current element lies between min and max,
    # it can be part of the BST
    if minVal <= pre[preIndex[0]] <= maxVal:

        # Treat the current element as the root of
        # this subtree
        rootData = pre[preIndex[0]]
        preIndex[0] += 1

        buildBSThelper(preIndex, n, pre, minVal, rootData)
        buildBSThelper(preIndex, n, pre, rootData, maxVal)


def canRepresentBST(arr):

    # Set the initial min and max values
    minVal = float('-inf')
    maxVal = float('inf')

    # Start from the first element in
    # the array
    preIndex = [0]
    n = len(arr)

    buildBSThelper(preIndex, n, arr, minVal, maxVal)

    # If all elements are processed, it means the
    # array represents a valid BST
    return preIndex[0] == n


# Driver Code
if __name__ == "__main__":

    arr = [40, 30, 35, 80, 100]

    if canRepresentBST(arr):
        print("true")
    else:
        print("false")
C#
using System;
using System.Collections.Generic;

public class GFG {

    static void buildBSThelper(ref int preIndex, int n,
                               List<int> pre, int min,
                               int max)
    {

        // If we have processed all elements, return
        if (preIndex >= n)
            return;

        // If the current element lies between min and max,
        // it can be part of the BST
        if (min <= pre[preIndex] && pre[preIndex] <= max) {

            // Treat the current element as the root of
            // this subtree
            int rootData = pre[preIndex];
            preIndex++;

            buildBSThelper(ref preIndex, n, pre, min,
                           rootData);
            buildBSThelper(ref preIndex, n, pre, rootData,
                           max);
        }
    }

    static bool canRepresentBST(List<int> arr)
    {

        // Set the initial min and max values
        int min = int.MinValue;
        int max = int.MaxValue;

        // Start from the first element in
        // the array
        int preIndex = 0;
        int n = arr.Count;

        buildBSThelper(ref preIndex, n, arr, min, max);

        // If all elements are processed, it means the
        // array represents a valid BST
        return preIndex == n;
    }

    // Driver Code
    public static void Main()
    {

        List<int> arr
            = new List<int>{ 40, 30, 35, 80, 100 };

        if (canRepresentBST(arr))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function buildBSThelper(preIndex, n, pre, min, max)
{

    // If we have processed all elements, return
    if (preIndex.index >= n)
        return;

    // If the current element lies between min and max,
    // it can be part of the BST
    if (min <= pre[preIndex.index]
        && pre[preIndex.index] <= max) {

        // Treat the current element as the root of
        // this subtree
        let rootData = pre[preIndex.index];
        preIndex.index++;

        buildBSThelper(preIndex, n, pre, min, rootData);
        buildBSThelper(preIndex, n, pre, rootData, max);
    }
}

function canRepresentBST(arr)
{

    // Set the initial min and max values
    let min = -Infinity, max = Infinity;

    // Start from the first element in
    // the array
    let preIndex = {index : 0};
    let n = arr.length;

    buildBSThelper(preIndex, n, arr, min, max);

    // If all elements are processed, it means the
    // array represents a valid BST
    return preIndex.index === n;
}

// Driver Code
let arr = [ 40, 30, 35, 80, 100 ];

if (canRepresentBST(arr))
    console.log("true");
else
    console.log("false");

Output
true
Comment