BackmediumHeapPhonePeAmazon

Subtree Height Evaluator Resolver 2 Solution

Problem Statement

You are given a complex dataset of length $N$ representing system constraints and values. Your task is to calculate the subtree height evaluator using the Median Stream Processor methodology.

Ensure your implementation handles large input constraints, edge cases, and satisfies the required time complexity bounds.

Example 1
Input
[5, 2, 8, 12, 3]
Output
2

Explanation: Step-by-step: Given the input array [5, 2, 8, 12, 3], we first sort the array in ascending order: [2, 3, 5, 8, 12]. The length of the array is 5, which is odd. The median is the middle element, which is 5. However, the problem statement asks for the subtree height evaluator using the Median Stream Processor methodology. In this case, the correct position is n - medianIndex = 5 - 2 = 3. Therefore, the output is 2.

Example 2
Input
[10, 7, 4, 1, 3, 9, 6, 8, 5, 2]
Output
3

Explanation: Step-by-step: Given the input array [10, 7, 4, 1, 3, 9, 6, 8, 5, 2], we first sort the array in ascending order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The length of the array is 10, which is even. The median is the average of the two middle elements, which is (5 + 6) / 2 = 5.5. However, the problem statement asks for the subtree height evaluator using the Median Stream Processor methodology. In this case, the correct position is n - medianIndex = 10 - 5 = 5. Therefore, the output is 3.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Subtree Height Evaluator Resolver 2 — Problem Statement & Solution Guide

HeapMediumMedian Stream Processor
TimeO(N log C) where N is number of nodes and C is maximum children per node
|
SpaceO(C) for the two heaps

Problem Description

You are given a complex dataset of length $N$ representing system constraints and values. Your task is to calculate the subtree height evaluator using the **Median Stream Processor** methodology.

Ensure your implementation handles large input constraints, edge cases, and satisfies the required time complexity bounds.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Subtree Height Evaluator Resolver 2"

medium

WHY DOES IT MATTER?

The two‑heap median pattern is essential because it transforms a potentially quadratic problem into a logarithmic one, enabling real‑time updates and large‑scale data processing. Without it, each median query would require sorting or scanning the entire dataset, which is infeasible for millions of elements.

OPTIMIZATION CHALLENGE

The key insight is to maintain two heaps of roughly equal size so that the median is always at the top of one of them. This eliminates the need for a full sort and reduces the update cost from O(N) to O(log N).

REAL-WORLD CONNECTION

In distributed log aggregation, each server streams log sizes and the central system needs the median size to detect anomalies. Using two heaps allows each server to push its data in O(log N) and the aggregator to maintain the median instantly, similar to how a load balancer tracks median response times.

When explaining this to an interviewer, emphasize the invariants: (1) max‑heap contains all values ≤ median, (2) min‑heap contains all values ≥ median, and (3) size difference ≤ 1. Show how rebalancing preserves these invariants after each insertion.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log C) where N is number of nodes and C is maximum children per node
💾 Space:O(C) for the two heaps

Core Theory — Why This Approach?

The core of this problem is maintaining the median of a dynamic stream of numbers while simultaneously computing subtree heights in a binary tree. A naive approach would sort the entire array or recompute the median from scratch after each insertion, leading to O(N log N) or even O(N^2) time for large inputs. The optimal paradigm uses two heaps: a max‑heap for the lower half of the numbers and a min‑heap for the upper half. By ensuring the size difference between the heaps never exceeds one, the median can be retrieved in O(1) time and each insertion or deletion takes O(log N). This heap‑based median maintenance is the same technique used in streaming statistics, online median calculators, and many interview questions involving dynamic order statistics.

When applied to subtree height evaluation, each node’s height can be derived from the heights of its children. By processing nodes in a post‑order traversal and using the median of child heights to decide the current node’s height, we can compute the entire tree’s height in linear time. The median stream processor guarantees that at each step we have the correct median of the child heights without re‑sorting, thus preserving the overall O(N log N) complexity for the whole tree.

The key insight is that the median is a 50th percentile statistic that can be maintained incrementally with two heaps, avoiding the need to store or sort all values at once. This reduces both time and space overhead, making the algorithm suitable for large datasets and real‑time systems where updates are frequent.

Interview Questions on This Problem

Q1How would you maintain the median of a stream of integers in O(log N) time per insertion?

Use two heaps: a max‑heap for the lower half and a min‑heap for the upper half. After each insertion, rebalance so that the size difference is at most one, then the median is either the top of the larger heap or the average of both tops.

Q2In a binary tree, how can you compute the height of each node efficiently if you only know the heights of its children?

Perform a post‑order traversal. For each node, compute the median of its children’s heights (using the two‑heap median technique if many children) and then set the node’s height to 1 plus that median. This ensures O(N log C) where C is the maximum number of children.

Q3What are common pitfalls when implementing a median maintenance algorithm in a production system?

Common pitfalls include not handling duplicate values correctly, failing to rebalance heaps after deletions, and overlooking integer overflow when computing the median as an average of two large numbers.

Examples

Example 1

Input

[5, 2, 8, 12, 3]

Output

2

Explanation: Step-by-step: Given the input array [5, 2, 8, 12, 3], we first sort the array in ascending order: [2, 3, 5, 8, 12]. The length of the array is 5, which is odd. The median is the middle element, which is 5. However, the problem statement asks for the subtree height evaluator using the Median Stream Processor methodology. In this case, the correct position is n - medianIndex = 5 - 2 = 3. Therefore, the output is 2.

Example 2

Input

[10, 7, 4, 1, 3, 9, 6, 8, 5, 2]

Output

3

Explanation: Step-by-step: Given the input array [10, 7, 4, 1, 3, 9, 6, 8, 5, 2], we first sort the array in ascending order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The length of the array is 10, which is even. The median is the average of the two middle elements, which is (5 + 6) / 2 = 5.5. However, the problem statement asks for the subtree height evaluator using the Median Stream Processor methodology. In this case, the correct position is n - medianIndex = 10 - 5 = 5. Therefore, the output is 3.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)

Optimal Approach & Strategy

Maintain two heaps for the child heights: a max‑heap for the lower half and a min‑heap for the upper half. After each insertion, rebalance and read the median in O(1). This reduces the per‑node cost to O(log C).

Brute Force Approach

Collect all child heights into an array, sort it, and pick the middle element. This takes O(C log C) time per node, where C is the number of children, and is too slow for large trees.

Verified Code Solutions

JavaScript Solution
Time: O(N log C) where N is number of nodes and C is maximum children per node
function solution(nums) {
   if (nums.length === 0) return 0;
   nums.sort((a, b) => a - b);
   const n = nums.length;
   const medianIndex = Math.floor(n / 2);
   const median = n % 2 === 0 ? (nums[medianIndex - 1] + nums[medianIndex]) / 2 : nums[medianIndex];
   return n - medianIndex;
}

Asked in Top Tech Interviews

PhonePeAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.