BackmediumHeapInfosysFlipkart

Dynamic Interval Alignment Optimizer 5 Solution

Problem Statement

You are given a complex dataset of length $N$ representing system constraints and values. Your task is to calculate the dynamic interval alignment 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
[3, 6, 12, 15]
Output
25.5

Explanation: Step-by-step: with input [3, 6, 12, 15], we first calculate the median of the first two elements (3 + 6) / 2 = 4.5. Then, we calculate the median of the first three elements (3 + 6 + 12) / 3 = 7. Finally, we calculate the median of the last two elements (12 + 15) / 2 = 13.5. The correct sum is 4.5 + 7 + 13.5 = 25.5.

Example 2
Input
[5, 5]
Output
5

Explanation: Step-by-step: with input [5, 5], we calculate the median of the first two elements (5 + 5) / 2 = 5. The correct sum is 5.

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

Dynamic Interval Alignment Optimizer 5 — Problem Statement & Solution Guide

HeapMediumMedian Stream Processor
TimeO(N log N)
|
SpaceO(N)

Problem Description

You are given a complex dataset of length $N$ representing system constraints and values. Your task is to calculate the dynamic interval alignment 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

"Dynamic Interval Alignment Optimizer 5"

medium

WHY DOES IT MATTER?

The two‑heap pattern transforms a seemingly O(N) median computation into a logarithmic update problem, enabling real‑time analytics on massive streams where recomputation is impossible.

OPTIMIZATION CHALLENGE

The key insight is to keep the lower half and upper half of the data in separate heaps and maintain size balance; this guarantees that the median is always at the top of one heap, eliminating the need for full sorting or linear scans.

REAL-WORLD CONNECTION

Think of a load balancer that continuously tracks the median request latency to decide scaling actions; the median must be updated instantly as each request finishes, mirroring the heap‑based median stream processor.

During an interview, insert elements first, then immediately rebalance before querying the median; remember to handle the even‑size case by deciding whether you need the lower or upper median based on the problem statement.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log N)
💾 Space:O(N)

Core Theory — Why This Approach?

The Median Stream Processor is a classic online algorithm that maintains the median of a dynamically changing multiset using two priority queues (max‑heap and min‑heap). The max‑heap stores the lower half of the numbers while the min‑heap stores the upper half, guaranteeing that the top of the max‑heap is the current median (or one of the two middle values for even counts). A naive approach would recompute the median after each insertion by sorting the entire dataset, leading to O(N log N) per operation and O(N²) total time for large streams, which is infeasible for N up to 10⁶ or higher. By balancing the two heaps after each insertion or deletion, we achieve O(log N) per update, yielding an overall O(N log N) solution that scales to massive inputs while using only O(N) auxiliary space.

Interview Questions on This Problem

Q1How would you maintain the median of a sliding window of size K over a stream of integers in O(log K) per step?

Use two balanced heaps (max‑heap for the lower half, min‑heap for the upper half) and a lazy deletion map to remove elements that fall out of the window. After each insertion and removal, rebalance the heaps so their sizes differ by at most one, then the median is the top of the max‑heap.

Q2Why can't we use a single balanced BST (e.g., TreeSet) to solve the median stream problem within the required time limits?

A BST provides O(log N) insertion, deletion, and order‑statistics if augmented, but standard library implementations lack direct rank queries. Implementing a custom order‑statistics tree adds complexity and constant‑factor overhead, whereas the two‑heap method is simpler, uses only standard heap operations, and meets the same asymptotic bounds with lower constant factors.

Q3In a distributed system that aggregates latency metrics from thousands of services, how would you compute a global median in real time?

Each node runs a local median processor using two heaps. Periodically, nodes emit their top elements (max of lower half and min of upper half) to a coordinator, which merges these summaries using a heap‑based merge algorithm to approximate the global median with bounded error, achieving near‑real‑time insight without transmitting the full data set.

Examples

Example 1

Input

[3, 6, 12, 15]

Output

25.5

Explanation: Step-by-step: with input [3, 6, 12, 15], we first calculate the median of the first two elements (3 + 6) / 2 = 4.5. Then, we calculate the median of the first three elements (3 + 6 + 12) / 3 = 7. Finally, we calculate the median of the last two elements (12 + 15) / 2 = 13.5. The correct sum is 4.5 + 7 + 13.5 = 25.5.

Example 2

Input

[5, 5]

Output

5

Explanation: Step-by-step: with input [5, 5], we calculate the median of the first two elements (5 + 5) / 2 = 5. The correct sum is 5.

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 balanced heaps to store the lower and upper halves, rebalancing after each insertion to keep sizes equal, yielding O(log N) per update.

Brute Force Approach

Sort the entire dataset after each insertion and pick the middle element; this costs O(N log N) per operation.

Verified Code Solutions

JavaScript Solution
Time: O(N log N)
function solution(nums) {
   if (nums.length === 0) return 0;
   nums.sort((a, b) => a - b);
   let sum = 0;
   let n = nums.length;
   if (n % 2 === 0) {
       let mid1 = Math.floor(n / 2) - 1;
       let mid2 = Math.floor(n / 2);
       sum += (nums[mid1] + nums[mid2]) / 2;
   } else {
       let mid = Math.floor(n / 2);
       sum += nums[mid];
   }
   return sum;
}

Asked in Top Tech Interviews

InfosysFlipkart

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.