Skip to content

571. Find Median Given Frequency of Numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
WITH
  NumbersMetadata AS (
    SELECT
      *,
      SUM(frequency) OVER(ORDER BY num) AS running_frequency,
      (SUM(frequency) OVER()) / 2 AS median_frequency
    FROM Numbers
  )
SELECT AVG(num) AS median
FROM NumbersMetadata
WHERE median_frequency BETWEEN running_frequency - frequency AND running_frequency;