ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES

Answer a Streaming Median Interview Query

Learn how to answer a streaming median interview query using a clear C program.

AdvancedInterview patternRange and stream queries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
2.0 1.5 2.0 3.5 2.0 2.0 2.0

COMPLETE C PROGRAM

Complete C implementation

ads-streaming-median-interview.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int values[]={2,1,5,7,2,0,5},sorted[7],count=0;for(int i=0;i<7;i++){int position=count;while(position>0&&sorted[position-1]>values[i]){sorted[position]=sorted[position-1];position--;}sorted[position]=values[i];count++;if(count%2)printf("%.1f",sorted[count/2]*1.0);else printf("%.1f",(sorted[count/2-1]+sorted[count/2])/2.0);printf("%c",i==6?'\n':' ');}return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

2.0 1.5 2.0 3.5 2.0 2.0 2.0
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Insert each arrival into sorted order and report the middle one or average of the middle pair.
  3. Display the computed result.

Insert each arrival into sorted order and report the middle one or average of the middle pair.

EFFICIENCY

Time and space complexity

Time complexity

O(n^2) demonstration; O(n log n) with two heaps

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.