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.
1import java.util.*;
2
3public class LargeClasses {
4 public static List<String> findLargeClasses(List<Pair<String, String>> courses) {
5 Map<String, Integer> classCount = new HashMap<>();
6 for (Pair<String, String> course : courses) {
7 classCount.put(course.getValue(), classCount.getOrDefault(course.getValue(), 0) + 1);
8 }
9 List<String> result = new ArrayList<>();
10 for (Map.Entry<String, Integer> entry : classCount.entrySet()) {
11 if (entry.getValue() >= 5) {
12 result.add(entry.getKey());
13 }
14 }
15 return result;
16 }
17
18 public static void main(String[] args) {
19 List<Pair<String, String>> courses = Arrays.asList(
20 new Pair<>("A", "Math"),
21 new Pair<>("B", "English"),
22 new Pair<>("C", "Math"),
23 new Pair<>("D", "Biology"),
24 new Pair<>("E", "Math"),
25 new Pair<>("F", "Computer"),
26 new Pair<>("G", "Math"),
27 new Pair<>("H", "Math"),
28 new Pair<>("I", "Math")
29 );
30 System.out.println(findLargeClasses(courses));
31 }
32}
We use a HashMap
to store the count of students per class. As we iterate through the courses
list, we update the count for each class. After processing all entries, we iterate over the map entries to collect classes that have at least five students into a result
list.