↓Skip to main content
  1. LeetCode/

LeetCode 596: Classes With at Least 5 Students

·1 min· ·
LeetCode Easy Database
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2021-10-10

  • Submissions: Wrong Answer ×3 → Runtime Error → Wrong Answer → Accepted

Approach
#

As in LC 182 this filters groups (SQL Template 4): GROUP BY class with HAVING ... >= 5. Count distinct students, COUNT(DISTINCT student), so repeats do not count twice. The current problem makes (student, class) the primary key, so COUNT(*) also works, but DISTINCT is safer.

My Attempts
#

This took 6 submissions, all about duplicate rows:

  • The first versions used COUNT(class), and the 2021 test data listed the same student in the same class more than once, double counting them; attempt 1 also used SELECT *.
  • Trying FROM distinct(courses) to deduplicate was invalid syntax (RE).
  • Computing COUNT(DISTINCT student) in a subquery and filtering >= 5 outside passed; putting it straight into HAVING works without the subquery.

Solution
#

SELECT class
FROM Courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5;

Complexity
#

Grouping is O(n) or O(n log n).

Mistakes to Avoid
#

  • SELECT * with GROUP BY fails in strict mode; select only grouped columns.
  • Count distinct students with COUNT(DISTINCT student).

Interview Explanation
#

I group by class and keep classes with at least five distinct students via HAVING, using COUNT DISTINCT so repeated rows do not count twice.

Related

LeetCode 197: Rising Temperature
·1 min
LeetCode Easy Database
LeetCode 197 note: self-join Weather on a one-day date difference with today warmer; compare dates with DATEDIFF, never ids
LeetCode 595: Big Countries
·1 min
LeetCode Easy Database
LeetCode 595 note: filter with WHERE and OR for an area of at least 3 million or a population of at least 25 million
LeetCode 620: Not Boring Movies
·1 min
LeetCode Easy Database
LeetCode 620 note: odd id and description not ‘boring’, ordered by rating from high to low
LeetCode 175: Combine Two Tables
·1 min
LeetCode Easy Database
LeetCode 175 note: people without an address must still appear, so LEFT JOIN, leaving city and state NULL when unmatched
LeetCode 181: Employees Earning More Than Their Managers
·1 min
LeetCode Easy Database
LeetCode 181 note: self-join Employee on managerId = id to pair employees with managers, then compare salaries
LeetCode 182: Duplicate Emails
·1 min
LeetCode Easy Database
LeetCode 182 note: group by email and keep groups with HAVING COUNT(*) > 1