Maximum Binary Tree

MediumTreesmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an array nums of **distinct** integers, build its *maximum tree* recursively: - The root holds the largest value in the array. - The left subtree is the maximum tree of the elements to the **left** of that value. - The right subtree is the maximum tree of the elements to the **right** of it. - An empty range produces no node. Return the root; the grader serializes it in level order. The direct recursion is O(n^2) in the worst case; a monotonic stack builds it in O(n).

Examples

Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
6 is the maximum; [3,2,1] forms its left subtree (3 -> right 2 -> right 1) and [0,5] its right subtree (5 with left child 0).
Input: nums = [3,2,1]
Output: [3,null,2,null,1]
Each maximum is at the left edge, so every subtree hangs to the right.

Constraints

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • All values in nums are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems