Classes With at Least 5 Students — LeetCode 596 Python Solution

EasyDatabase
Problem
#596
Reading time
2 min

The problem

Report every class that has five or more students enrolled, in any order. The Courses table has one row per enrolment: student (varchar) and class (varchar), with the pair (student, class) as the primary key.

Example

Courses table:

| student | class   |
| ------- | ------- |
| Ada     | Math    |
| Bob     | Math    |
| Cara    | Math    |
| Dan     | Math    |
| Eve     | Math    |
| Ada     | Biology |
| Bob     | Biology |

Result:

| class |
| ----- |
| Math  |

Math has five enrolments and clears the bar; Biology has two and does not.

Python solution

Python
import pandas as pd

def classes_with_5_students(courses: pd.DataFrame) -> pd.DataFrame:
    counts = courses.groupby('class')['student'].nunique()
    res = counts[counts >= 5].reset_index()[['class']]
    return res

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 596. Classes With at Least 5 Students?
LeetCode 596. Classes With at Least 5 Students is rated Easy on LeetCode.
What topics does LeetCode 596. Classes With at Least 5 Students cover?
LeetCode 596. Classes With at Least 5 Students is tagged Database on LeetCode.

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