#2356
Number of Unique Subjects Taught by Each Teacher
EasyDatabaseHash MapSet
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap to efficiently count unique subjects for each teacher in a single pass through the data, significantly reducing the time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a HashMap to store each teacher's unique subjects.
- 2Step 2: Iterate through each row in the teacher table.
- 3Step 3: For each teacher_id, add the subject_id to the HashMap's set of subjects.
- 4Step 4: After processing all rows, create a result list from the HashMap.
- 5Step 5: Return the result list.
solution.py11 lines
1# Full working Python code
2import pandas as pd
3
4def count_unique_subjects(teacher_df):
5 subject_count = {}
6 for _, row in teacher_df.iterrows():
7 if row['teacher_id'] not in subject_count:
8 subject_count[row['teacher_id']] = set()
9 subject_count[row['teacher_id']].add(row['subject_id'])
10 result = [{'teacher_id': teacher, 'cnt': len(subjects)} for teacher, subjects in subject_count.items()]
11 return pd.DataFrame(result)ℹ
Complexity note: The time complexity is O(n) because we only go through the list of teachers once. The space complexity is O(n) due to the storage of unique subjects in the HashMap.
- 1Using a HashMap allows for efficient counting of unique items without needing nested loops.
- 2Sets are useful for automatically handling duplicates when counting unique subjects.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.