1639. Search Tree by Floors

A librarian once recorded book ids by walking a shelf tree floor by floor, left to right on each floor, but the tree itself was lost and only the list arr of distinct ids remains. A search tree here is a binary tree in which every id in a node's left subtree is smaller than the node and every id in its right subtree is larger.

Decide whether arr could be the level-order traversal (top floor to bottom, left to right within a floor) of some search tree that contains exactly these ids. Return true if such a tree exists, otherwise false.

All ids are distinct and arr has at least one element; a single id is always valid. Aim for O(n) time and O(n) extra space. You do not need to build the tree explicitly.

Example 1

Input:
arr = [8,3,10,1,6,14]
Output:
true
Explanation:

Building greedily gives 8 with children 3 and 10, then 1 and 6 under 3, and 14 under 10, a valid search tree.

Example 2

Input:
arr = [2,3,1]
Output:
false
Explanation:

After 3 becomes the right child of 2, the value 1 is smaller than 2 and has no free slot.

Example 3

Input:
arr = [8,3,10,14,1]
Output:
false
Explanation:

14 can only go right of 10, and then 1 cannot be placed anywhere.

Constraints

1 ≤ n ≤ 1000

keys distinct in [-109, 109]

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…