Cartesian Tree Builder - Problem

Build a Cartesian Tree from an array of integers in O(n) time using a stack-based approach. A Cartesian Tree is a binary tree derived from a sequence of numbers with these properties:

1. Binary Search Tree (BST) property: In-order traversal gives the original array sequence

2. Min-Heap property: Each parent node has a value smaller than both children

Your task is to construct the tree and verify both properties hold. Return a list containing two boolean values: [isBST, isMinHeap] where the first indicates if the BST property holds and the second indicates if the min-heap property holds.

Note: The tree structure is uniquely determined by the array values and their positions.

Input & Output

Example 1 — Basic Case
$ Input: arr = [3,1,6,4,5]
Output: [true,true]
💡 Note: Cartesian tree has 1 as root (minimum), 3 as left child, and 6,4,5 form right subtree. In-order traversal gives [3,1,6,4,5] (BST property ✓) and all parents are smaller than children (min-heap property ✓)
Example 2 — All Increasing
$ Input: arr = [1,2,3,4,5]
Output: [true,true]
💡 Note: Creates a right-skewed tree with 1 as root. In-order traversal: [1,2,3,4,5] (BST ✓). Each parent < children (min-heap ✓)
Example 3 — All Decreasing
$ Input: arr = [5,4,3,2,1]
Output: [true,true]
💡 Note: Creates a left-skewed tree with 1 as root at the end. In-order: [5,4,3,2,1] (BST ✓). Min-heap property holds (min-heap ✓)

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 1 ≤ arr[i] ≤ 1000
  • All elements in arr are distinct

Visualization

Tap to expand
INPUT ARRAYSTACK ALGORITHMRESULT TREE31645Array: [3,1,6,4,5]Distinct integersNeed BST + Min-Heap1234Stack tracksrightmost pathPop > currentConnect nodesO(n) time13645BST ✓ Min-Heap ✓[true, true]-->-->Key Insight:Stack maintains rightmost path during construction, allowing O(n) timecomplexity as each element is pushed and popped exactly once.TutorialsPoint - Cartesian Tree Builder | Stack-Based O(n) Construction
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
25.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen