Sponsored
Sponsored
The simplest solution to this problem is to exploit SQL's GROUP BY
feature alongside the COUNT()
function. We'll group students by their class, count the number of students in each group, and then filter those results to include only classes with five or more students.
Time Complexity: O(n), where n is the number of rows in the table, because we need to check each row to perform the GROUP BY
operation.
Space Complexity: O(k), where k is the number of unique classes in the output.
1SELECT class FROM Courses GROUP BY class HAVING COUNT(student) >= 5;
This SQL query begins with selecting the class
from the Courses
table. Then, we group the entries by class
and use the COUNT()
function to count the number of students associated with each class. Finally, we use HAVING
to filter down to only those classes where the student count is at least five.
In languages like C, C++, Java, Python, C#, and JavaScript, we can simulate the SQL behavior with a hashmap (dictionary in Python, or an object in JavaScript). We iterate through the data, count the occurrences of each class, and then extract the classes that have counts of five or more.
Time Complexity: O(n), where n is the number of entries in the courses list, as we iterate through all entries once.
Space Complexity: O(k), the number of distinct classes, because of the hashmap.
1def find_large_classes(courses):
2 from collections import defaultdict
3 class_count = defaultdict(int)
4
5 for student, clss in courses:
6 class_count[clss] += 1
7
8 result = [clss for clss, count in class_count.items() if count >= 5]
9 return result
10# courses = [('A', 'Math'), ('B', 'English'), ('C', 'Math'), ('D', 'Biology'), ('E', 'Math'), ('F', 'Computer'), ('G', 'Math'), ('H', 'Math'), ('I', 'Math')]
11# print(find_large_classes(courses))
We use a defaultdict
from Python's collections
module to store each class's student count. As we iterate through the list of tuples courses
, we increment the count for the class each student is enrolled in. Finally, we build a result list of classes that have a count of at least five.