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
13d

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!
Add answer anonymously...
Cadence Design Systems Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter