EasyNo. 0596

Classes With at Least 5 Students — LeetCode 596 Python Solution

Topics
Database
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

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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

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.

Free to download. Check it runs on your machine, then pick a plan.