Find Median Given Frequency of Numbers — LeetCode 571 Python Solution

HardLeetCode PremiumDatabase
Problem
#571
Reading time
3 min

Table schema

SQL
Table: Numbers +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | | frequency | int | +-------------+------+ num is the primary key (column with unique values) for this table. Each row of this table shows the frequency of a number in the database.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| num         | int  |
| frequency   | int  |
+-------------+------+
num is the primary key (column with unique values) for this table.
Each row of this table shows the frequency of a number in the database.

Python solution

Python
import pandas as pd

def median_from_frequencies(numbers: pd.DataFrame) -> pd.DataFrame:
    df = numbers.sort_values('num')
    df['cum'] = df['frequency'].cumsum()
    total = int(df['frequency'].sum())
    if total == 0:
        return pd.DataFrame({'median': []})
    if total % 2 == 1:
        pos = (total + 1) // 2
        median = df.loc[df['cum'] >= pos, 'num'].iloc[0]
    else:
        pos1 = total // 2
        pos2 = pos1 + 1
        m1 = df.loc[df['cum'] >= pos1, 'num'].iloc[0]
        m2 = df.loc[df['cum'] >= pos2, 'num'].iloc[0]
        median = (m1 + m2) / 2
    return pd.DataFrame({'median': [float(median)]})

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 571. Find Median Given Frequency of Numbers?
LeetCode 571. Find Median Given Frequency of Numbers is rated Hard on LeetCode.
What topics does LeetCode 571. Find Median Given Frequency of Numbers cover?
LeetCode 571. Find Median Given Frequency of Numbers is tagged Database on LeetCode.
Is LeetCode 571. Find Median Given Frequency of Numbers a premium problem?
Yes. LeetCode 571. Find Median Given Frequency of Numbers is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview