Find Median Given Frequency of Numbers - Problem

You are given a table Numbers with the following structure:

  • num: The actual number (primary key)
  • frequency: How many times this number appears

The median is the value separating the higher half from the lower half of a data sample. When we "decompress" the table by repeating each number according to its frequency, we need to find the median of all these numbers.

Write a SQL solution to find the median of all numbers after decompressing the table. Round the result to one decimal place.

Table Schema

Numbers
Column Name Type Description
num PK int The actual number value (primary key)
frequency int How many times this number appears
Primary Key: num
Note: Each row shows a unique number and its frequency in the dataset

Input & Output

Example 1 — Basic Median Calculation
Input Table:
num frequency
0 7
1 1
2 3
Output:
median
0
💡 Note:

After decompressing: [0,0,0,0,0,0,0,1,2,2,2] (11 numbers total). The median is the 6th number when sorted, which is 0. Result: 0.0

Example 2 — Even Count Median
Input Table:
num frequency
1 2
2 2
Output:
median
1.5
💡 Note:

After decompressing: [1,1,2,2] (4 numbers total). The median is the average of 2nd and 3rd numbers: (1+2)/2 = 1.5

Example 3 — Single Number Multiple Times
Input Table:
num frequency
5 10
Output:
median
5
💡 Note:

All 10 numbers are 5. The median of [5,5,5,5,5,5,5,5,5,5] is clearly 5.0

Constraints

  • 1 ≤ Numbers.num ≤ 500
  • 1 ≤ Numbers.frequency ≤ 10^4
  • The total frequency is guaranteed to be at least 1
  • Round the median to one decimal place

Visualization

Tap to expand
Find Median Given Frequency of Numbers INPUT num frequency 0 7 1 1 2 3 3 1 Decompressed: [0,0,0,0,0,0,0,1,2,2,2,3] Total count: 12 Positions: 1 to 12 0 0 0 0 0 0 0 1 2 2 2 3 pos 1 pos 12 ALGORITHM STEPS 1 Calculate Total Sum frequencies: 7+1+3+1=12 2 Find Median Position Pos = (12+1)/2 = 6.5 Need pos 6 and 7 3 Cumulative Sum Track running total 0 1 2 3 7 8 11 12 4 Find Median Value Pos 6,7 both in num=0 (cumsum 7 >= 6,7) Median = (0 + 0) / 2 = 0 FINAL RESULT Sorted sequence with positions: 0 0 0 0 0 0 0 1 2 2 2 3 ^ ^ 6 7 Median positions: 6 and 7 Both positions have value: 0 MEDIAN 0.0 OK - Verified Rounded to 1 decimal Key Insight: Use cumulative frequency to find median position without decompressing the array. For even total (n), median = average of values at positions n/2 and (n/2)+1. Time: O(n), Space: O(1) - No need to expand the frequency table into full array. TutorialsPoint - Find Median Given Frequency of Numbers | Optimal Solution
Asked in
Amazon 12 Google 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen