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.
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
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
2.0 1.5 2.0 3.5 2.0 2.0 2.0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Insert each arrival into sorted order and report the middle one or average of the middle pair.
- 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.
