Median in a stream
Given that integers are read from a data stream. Your task is to find the median of the elements read so far.
Median is the middle value in an ordered integer list. If the size of the list is even there is no middle value. So the median is the floor of the average of the two middle values.
For example :
[2,3,4] - median is 3.
[2,3] - median is floor((2+3)/2) = 2.
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains the number of elements, N, in the input data stream.
The second line of each test case contains N space separated elements of the input data stream.
Output Format:
For each test case, print the median of the elements after each incoming element. Each median value is separated by a single space.
The output of each test case is printed in a separate line.
Note :
You do not need to print anything, just return the vector of medians after each element is read from the stream.
Constraints :
1 <= T <= 10
1 <= N <= 10^4
0 <= data <= 10^8
Where T is the number of test cases, N is the number of elements in the data stream.
Time Limit : 1 sec
CodingNinjas
author
2y
Brute force approach
Store the incoming data elements in a vector. Sort the vector everytime you need to output the median.
Algorithm:
- Store the incoming elements of the data stream in a vector.
- Step by s...read more
CodingNinjas
author
2y
Insertion sort approach
If we sort the data as it appears, the median can be located easily. Insertion Sort is one such algorithm that sorts the data appeared so far. At any instance of sorting, say af...read more
CodingNinjas
author
2y
Heap based approach
The idea is to use two heaps, one max - heap and one min - heap. The max-heap will be used to represent elements that are less than the effective median, and min-heap will be used t...read more
Add answer anonymously...
Top Amazon SDE-2 interview questions & answers
Popular interview questions of SDE-2
Top HR questions asked in Amazon SDE-2
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app