Check If Preorder Traversal Is Valid

Determine whether a given array ARR of positive integers is a valid Preorder Traversal of a Binary Search Tree (BST).

A binary search tree (BST) is a tree structure where each node's value is greater than all values in its left subtree and less than all values in its right subtree.

Input:

The first line contains an integer, 'T', representing the number of test cases.
The first line of each test case consists of an integer 'N', indicating the number of elements in the array 'ARR'.
The second line contains 'N' space-separated integers representing the elements of the array 'ARR'.

Output:

For each test case, output 1 if the array is a valid preorder traversal of a BST; otherwise, output 0.
Each result should be on a new line.

Example:

Input:
2
3
7 4 8
3
1 5 3
Output:
1
0
Explanation:

For the first test case, the sequence 7 4 8 can represent a BST, while for the second test case, the sequence 1 5 3 cannot.

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 105
  • 0 ≤ ARR[i] ≤ 109

Note: You do not need to print anything. Just implement the function as described.

AnswerBot
4mo

Check if a given array of positive integers is a valid Preorder Traversal of a Binary Search Tree (BST).

  • Create a stack to keep track of nodes.

  • Iterate through the array and compare each element with th...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Cadence Design Systems

Q. Given an array, reverse the order of its elements in place.
Q. Given the coordinates of a point and a rectangle, how would you determine if the...read more
Q. You are given an array of elements. Some or all of them are duplicates. Find the...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits