Menu
CoddyTech

Find Median from Data Stream

HardHeappython iconjava iconcpp iconc iconjs icon+10

Design a structure with two operations: addNum stores an integer, and findMedian returns the median of all values stored so far. The median of an odd count is the middle value; for an even count it is the average of the two middle values.

Operation i is ops[i], with values[i] holding the number for an addNum and 0 for a findMedian. Run them in order on an empty structure and return one string each: "null" for addNum, the median for findMedian. Write the median like "3", "2.5" or "-0.5": no decimal point for a whole number, and zero as "0", never "-0".

Function

medianStreamOps(ops: string-array, values: integer-array) → string-array
opsstring-array
the operations, in the order they run
valuesinteger-array
the number for each addNum, 0 for each findMedian
Returnsstring-array
one answer per operation, as text

Constraints

  • 1 ≤ ops.length ≤ 3000
  • values.length == ops.length
  • Every ops[i] is addNum or findMedian.
  • -105 ≤ values[i] ≤ 105 for addNum, and values[i] == 0 for findMedian.
  • findMedian is only called after at least one addNum.

Examples

Input
ops = ["addNum", "findMedian", "addNum", "findMedian", "addNum", "findMedian", "addNum", "findMedian"]values = [5, 0, 1, 0, 8, 0, 3, 0]
Output
["null", "5", "null", "3", "null", "5", "null", "4"]
Explanation
With 1 and 5 the median is (1 + 5) / 2 = 3. With 1, 5 and 8 it is 5, and with 1, 3, 5 and 8 it is (3 + 5) / 2 = 4.
challenge icon

Follow-up

If every value were between 0 and 100, how could you make both operations run in constant time?

Reset code
def medianStreamOps(ops, values):
    # Write code here

Test #1

Test #2

Arguments

ops = ["addNum", "findMedian", "addNum", "findMedian", "addNum", "findMedian", "addNum", "findMedian"]
values = [5, 0, 1, 0, 8, 0, 3, 0]

Expected Output

["null", "5", "null", "3", "null", "5", "null", "4"]