#596

Classes With at Least 5 Students

Easy
DatabaseHash MapAggregation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using SQL's GROUP BY and HAVING clauses allows us to efficiently group students by class and filter those with at least five students in a single query. This is more efficient than checking each class individually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use GROUP BY to group records by class.
  2. 2Step 2: Use COUNT to count the number of students in each class.
  3. 3Step 3: Use HAVING to filter groups with a count of 5 or more.
solution.py1 lines
1SELECT class FROM Courses GROUP BY class HAVING COUNT(student) >= 5;

Complexity note: The time complexity is O(n) because we only need to scan the data once to group and count students, which is much more efficient.

  • 1Using GROUP BY and HAVING in SQL can significantly reduce the complexity of counting and filtering operations.
  • 2Understanding how to aggregate data is crucial for efficiently solving problems involving counts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.