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 NumbersInput: Numbersnumfrequency071123Compressed dataFINDMEDIANOutput: Median0.0Median of decompressed data:[0,0,0,0,0,0,0,1,2,2,2]Algorithm Steps:1. Calculate total count: 7 + 1 + 3 = 112. Median position: (11 + 1) / 2 = 6th element3. Use cumulative frequency to find position 64. Position 6 falls in first group (num=0)
Understanding the Visualization
1
Input
Numbers table with frequency counts
2
Cumulate
Calculate running frequency totals
3
Locate
Find median position and return result
Key Takeaway
🎯 Key Insight: Use cumulative frequencies to find median position without expanding compressed data
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