Sponsored
Sponsored
This approach utilizes hash maps (or dictionaries) to store the relationship between teachers and the unique subjects they teach. The usage of sets facilitates the storage of unique subject IDs for each teacher. After accumulating the subjects for each teacher, counting the number of unique subjects can easily be done by checking the length of each set.
This method will efficiently group, count, and return the results.
Time Complexity: O(n), where n is the number of records in the input table, assuming average O(1) time complexity for set operations.
Space Complexity: O(m), where m is the number of unique (teacher_id, subject_id) pairs.
1# Python solution
2from collections import defaultdict
3
4def count_unique_subjects(teacher_records):
5 teacher_to_subjects = defaultdict(set)
6 for record in teacher_records:
7 teacher_id, subject_id, _ = record
8 teacher_to_subjects[teacher_id].add(subject_id)
9
10 result = []
11 for teacher_id, subjects in teacher_to_subjects.items():
12 result.append((teacher_id, len(subjects)))
13 return result
14
15# Example input
16teacher_records = [
17 (1, 2, 3),
18 (1, 2, 4),
19 (1, 3, 3),
20 (2, 1, 1),
21 (2, 2, 1),
22 (2, 3, 1),
23 (2, 4, 1)
24]
25
26# Function call
27print(count_unique_subjects(teacher_records))
This Python solution uses a defaultdict of sets to accumulate subject IDs for each teacher. The key point here is using a set, which inherently ensures that only unique subjects are stored. After building the map of teacher ID to subject sets, we simply count the number of unique subjects by measuring the length of each set corresponding to a teacher and prepare the result list.
This approach imitates SQL operations by using arrays or similar data structures to first group data by teacher and then reducing the grouped data to count the unique subjects for each group. This approach can use sorting and manual iteration to simulate a GROUP BY operation.
Time Complexity: O(n) due to single-pass processing and set operations.
Space Complexity: O(m) corresponding to unique (teacher_id, subject_id) pairs.
1// Java solution
2import java.util.*
teacherToSubjects
In this Java solution, we simulate SQL GROUP BY and aggregation using Java collections such as HashMap and HashSet. The key for the map is the teacher ID, and the value is a set that contains unique subject IDs. The solution iterates over the input data, populating the map accordingly and then measures the size of each set to get the count of unique subjects per teacher.