Microsoft Interview Question
Software Engineer / DevelopersTeam: windows
Country: United States
Interview Type: In-Person
Yep, this is more or less the optimal solution. You can also do something similar with a binary tree.
hi all,
my answer was
1. create a BST and a counter.
2. each time you get a number insert it into the BST and increment the counter.
3. each node in the BST has a field "rank" that is the number of nodes in the subtree rooted at that node.
4. when median is asked return the node whose rank = counter/2 if counter is odd else return the node whose rank = (counter/2)-1
first the stream is 0,1,2,3,4. the tree will be
0(4)
\
1(3)
\
2(2)
\
3(1)
\
4(0)
counter = 5
now median is 2 as rank(2) = (counter/2).
now comes -2. the tree will be
0(5)
/ \
(0)-2 1(3)
\
2(2)
\
3(1)
\
4(0)
counter = 6
(counter/2)-1 = 2
median is node 2 as rank(2) = 2.
now comes -4. the tree will be
0(6)
/ \
(1)-2 1(3)
/ \
(0)-4 2(2)
\
3(1)
\
4(0)
counter = 7
counter/2 = 3
median = 1 as rank(1) = 3
please tell me if there is any problem in this algorithm. please try it on some other examples and if you find anything not working properly then please notify.
thanking you all
since the range is always sorted median will be at n/2 always.
lets say the median value at the beginning ie Array[n/2] is k.
from here whenever you are inserting any value to the array check if that value is > k or <k.. ie are you inserting in left half or right half.. and keep count the number of insertion in left half and in right half.
At the end calculate l
j+(lefthalfcount -righthalfcount)/2..
j+k would be the next median.. please tell me if you see any mistake
to all of you who have implemented array to find the median : the input is a continuous string of integers. that means integers are coming continuously. so the number of integers tends to infinity theoretically and practically you are not obviously supposed to store them all in an ARRAY to find the median. if you do that then your program will crass after the memory is filled. this type of questions are asked to check if you are able to think of space complexity or not. so i would suggest never start with an array. it'll suddenly cost you negative points in the interviews.
and the answer of kill is the best described and the optimal one. my answer would work but i can get median in O(log n) time where kill can do it in O(1) time.
thanks friends for replying to this question.
since the range is always sorted median will be at n/2 always.
lets say the median value at the beginning ie Array[n/2] is k.
from here whenever you are inserting any value to the array check if that value is > k or <k.. ie are you inserting in left half or right half.. and keep count the number of insertion in left half and in right half.
At the end calculate l
j+(lefthalfcount -righthalfcount)/2..
j+k would be the next median.. please tell me if you see any mistake
There's an elegant solution(publicized, not my own) to this problem.
- kill February 01, 2012