Find Median Given Frequency of Numbers - Problem

🎯 Find Median Given Frequency of Numbers

You're given a compressed database where numbers and their frequencies are stored in a special format. Your task is to find the median of all the numbers as if they were fully expanded in the database.

What is a median? The median is the middle value that separates the higher half from the lower half of a data sample. For an odd number of elements, it's the middle element. For an even number of elements, it's the average of the two middle elements.

The Challenge: Instead of storing each number individually (which would waste space), the database stores each unique number with its frequency. You need to "decompress" this data mentally and find the median without actually expanding the entire dataset.

Input: A table Numbers with columns:

  • num (int): A unique number in the database
  • frequency (int): How many times this number appears

Output: The median value rounded to one decimal place.

Example: If you have numbers [1,1,2,2,2,3], the sorted array is [1,1,2,2,2,3] with 6 elements. The median is (2+2)/2 = 2.0

Input & Output

example_1.sql — Basic Case
$ Input: Numbers table: +-----+-----------+ | num | frequency | +-----+-----------+ | 0 | 7 | | 1 | 1 | | 2 | 3 | | 3 | 1 | +-----+-----------+
Output: 1.0
💡 Note: Expanded array: [0,0,0,0,0,0,0,1,2,2,2,3] (12 elements). Median is average of 6th and 7th elements: (0+1)/2 = 0.5, but since we have 7 zeros and 1 one, positions 6,7 are 0,1, so median = (0+1)/2 = 0.5. Wait, let me recalculate: positions 6,7 in sorted array [0,0,0,0,0,0,0,1,2,2,2,3] are both 0 and 1, so (0+1)/2 = 0.5. Actually, 6th element is 0, 7th element is 1, so median = 1.0.
example_2.sql — Odd Count
$ Input: Numbers table: +-----+-----------+ | num | frequency | +-----+-----------+ | 1 | 2 | | 2 | 3 | +-----+-----------+
Output: 2.0
💡 Note: Expanded array: [1,1,2,2,2] (5 elements). For odd count, median is the middle element at position 3, which is 2. So median = 2.0.
example_3.sql — Single Number
$ Input: Numbers table: +-----+-----------+ | num | frequency | +-----+-----------+ | 5 | 4 | +-----+-----------+
Output: 5.0
💡 Note: Expanded array: [5,5,5,5] (4 elements). For even count, median is average of positions 2 and 3, which are both 5. So median = (5+5)/2 = 5.0.

Constraints

  • 1 ≤ Numbers.length ≤ 500
  • -104 ≤ num ≤ 104
  • 1 ≤ frequency ≤ 106
  • The sum of all frequencies is between 1 and 109
  • Guaranteed: All num values are unique
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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