Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Find Median from Data Stream
MEDIUM
20 mins
Heap
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Heap
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Find Median from Data Stream

Contributed by
imObscure
Medium
yellow-spark
0/80
Avg time to solve 20 mins
Success Rate 76 %
Share
0 upvotes

Problem Statement

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

Example:
Median for ‘arr’ = [1,2,3,4,5] is 3.
Median for ‘arr’ = [1,2,3,4] is (2+3)/2 = 2.5.

Implement the MedianFinder class:

MedianFinder() initialises the MedianFinder object.

1. Void addNum(int ‘num’) adds the integer ‘num’ from the datastream to the data structure.

2. Double findMedian() returns the median of all elements so far.

Note : Answers within 10^-5 of actual answer will be accepted.

Example:
Input: 
5
1 1
1 2
2
1 5
2

Output:     
1.5
2

Explanation:
MedianFinder() initialises the MedianFinder object.
Add 1 to the data structure ‘arr’, so arr = [1].
Add 2 to arr, so arr = [1,2]
Find Median of current arr, that is (1+2)/2 = 1.5.
Add 5 to arr, so arr = [1,2,5]
Find Median of current arr, that is 2.0.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
2
5
1 1
1 2
2
1 5
2 
4
1 1
2
1 5
2
Sample Output 1 :
1.5
2
1
3
Explanation Of Sample Input 1 :
Test 1:
MedianFinder() initialises the MedianFinder object.
Add 1 to the data structure ‘arr’, so arr = [1].
Add 2 to arr, so arr = [1,2]
Find Median of the current arr, that is (1+2)/2 = 1.5.
Add 5 to arr, so arr = [1,2,5]
Find Median of current arr, that is 2.0

Test 2:
MedianFinder() initialises the MedianFinder object.
Add 1 to the data structure ‘arr’, so arr = [1].
Find Median of current arr, that is 1.0.
Add 5 to arr, so arr = [1,5]
Find Median of current arr, that is (1+5)/2 = 3.0.
Sample Input 2 :
2
4
1 1
1 5
1 2
2
5
1 1
1 5
2
1 3
2
Sample Output 2 :
2.0
3
3
Reset Code
Full screen
Auto
copy-code
Console