Number of Unique Subjects Taught by Each Teacher solution and explanation
9 more videos on this problem
Number of Unique Subjects Taught by Each Teacher | Leetcode 2356 | Crack SQL Interviews in 50 QsLearn With Chirag · 3:36 · 6K views
LeetCode 2356 "Unique Subjects Taught by Teacher" Capgemini Interview SQL Question with ExplanationEveryday Data Science · 3:12 · 1K views
LeetCode 2356: Number of Unique Subjects Taught by Each Teacher [SQL]Frederik Müller · 3:39 · 1K views
Solving LeetCode Problem 2356 - Number of Unique Subjects Taught by Each TeachervanAmsen · 4:58 · 183 views
2356. Number of Unique Subjects Taught by Each Teacher | Leetcode | HindiDataEngineering360 · 2:18 · 164 views
Решение задачи «2356. Number of Unique Subjects Taught by Each Teacher» на SQL с сайта leetcode.comVadim Kiselev · 3:05 · 87 views
2356. Number of Unique Subjects Taught by Each Teacher | SQL | Leetcode | Easy ExplainationSheCodes · 4:13 · 74 views
LeetCode SQL50 | Day 23 | 2356. Number of Unique Subjects Taught by Each TeacherA for Analysis · 1:32 · 51 views
2356. Number of Unique Subjects Taught by Each Teacher | SQL 50 | LEETCODE STUDY PLANRandomCoding · 3:01 · 44 views
23. Leetcode 2356. Number of Unique Subjects Taught by Each Teacher : MYSQLWeb Fusion with Bharadwaj · 10:35 · 42 views
The problem
Table: Teacher
+-------------+------+ | Column Name | Type | +-------------+------+ | teacher_id | int | | subject_id | int | | dept_id | int | +-------------+------+ (subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table. Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.
Write a solution to calculate the number of unique subjects each teacher teaches in the university.
Return the result table in any order.
The result format is shown in the following example.
Example 1:
Input: Teacher table: +------------+------------+---------+ | teacher_id | subject_id | dept_id | +------------+------------+---------+ | 1 | 2 | 3 | | 1 | 2 | 4 | | 1 | 3 | 3 | | 2 | 1 | 1 | | 2 | 2 | 1 | | 2 | 3 | 1 | | 2 | 4 | 1 | +------------+------------+---------+ Output: +------------+-----+ | teacher_id | cnt | +------------+-----+ | 1 | 2 | | 2 | 4 | +------------+-----+ Explanation: Teacher 1: - They teach subject 2 in departments 3 and 4. - They teach subject 3 in department 3. Teacher 2: - They teach subject 1 in department 1. - They teach subject 2 in department 1. - They teach subject 3 in department 1. - They teach subject 4 in department 1.
Approach overview
Problem Overview: You are given a table where each row represents a teacher teaching a specific subject. A teacher may appear multiple times if they teach multiple subjects. The task is to compute how many unique subjects each teacher teaches and return the result per teacher.
Approach 1: Using Hash Maps and Sets (O(n) time, O(n) space)
Iterate through every record and group subjects by teacher_id. Use a hash map where the key is the teacher ID and the value is a set of subject IDs. As you process each row, insert the subject_id into the set for that teacher. Sets automatically remove duplicates, which guarantees that each subject is counted once. After processing all rows, compute the size of each set to get the number of unique subjects taught by that teacher.
This approach mirrors how you would solve the problem in application code rather than directly in SQL. It works well when the data is already loaded in memory (for example, inside a backend service or coding interview problem). Since each row is processed once and set insertion is O(1) on average, the overall time complexity is O(n) with O(n) space for storing grouped subjects.
Approach 2: SQL-like Grouping and Aggregation (O(n) time, O(k) space)
Database problems are naturally solved using database aggregation. Group all rows by teacher_id and compute the number of distinct subjects using COUNT(DISTINCT subject_id). The database engine scans the table, groups rows with the same teacher, and removes duplicate subject IDs within each group before counting.
This method leverages optimized database grouping operations and is the most natural solution when working directly with relational data. Internally, databases often use hashing or sorting to perform grouping, but the conceptual complexity remains O(n) time for scanning rows and roughly O(k) space where k is the number of teachers being grouped.
Recommended for interviews: Interviewers typically expect the grouping idea immediately. The hash map + set approach shows you understand how to simulate SQL aggregation using core data structures. In database-focused questions, the GROUP BY teacher_id with COUNT(DISTINCT subject_id) solution is the cleanest and most direct representation of the logic.
Approach 1: Approach 1: Using Hash Maps and Sets
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.
# Python solution
from collections import defaultdict
def count_unique_subjects(teacher_records):
teacher_to_subjects = defaultdict(set)
for record in teacher_records:
teacher_id, subject_id, _ = record
teacher_to_subjects[teacher_id].add(subject_id)
result = []
for teacher_id, subjects in teacher_to_subjects.items():
result.append((teacher_id, len(subjects)))
return result
# Example input
teacher_records = [
(1, 2, 3),
(1, 2, 4),
(1, 3, 3),
(2, 1, 1),
(2, 2, 1),
(2, 3, 1),
(2, 4, 1)
]
# Function call
print(count_unique_subjects(teacher_records))// JavaScript solution
function countUniqueSubjects(teacherRecords) {
const teacherToSubjects = {};
teacherRecords.forEach(([teacherId, subjectId]) => {
if (!teacherToSubjects[teacherId]) {
teacherToSubjects[teacherId] = new Set();
}
teacherToSubjects[teacherId].add(subjectId);
});
const result = [];
for (const [teacherId, subjects] of Object.entries(teacherToSubjects)) {
result.push({ teacher_id: +teacherId, cnt: subjects.size });
}
return result;
}
// Example input
const teacherRecords = [
[1, 2, 3],
[1, 2, 4],
[1, 3, 3],
[2, 1, 1],
[2, 2, 1],
[2, 3, 1],
[2, 4, 1]
];
// Function call
console.log(countUniqueSubjects(teacherRecords));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.
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.
Approach 2: Approach 2: SQL-like Grouping and Aggregation
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.
// Java solution
import java.util.*;
public class UniqueSubjects {
public static List<int[]> countUniqueSubjects(int[][] teacherRecords) {
Map<Integer, Set<Integer>> teacherToSubjects = new HashMap<>();
for (int[] record : teacherRecords) {
int teacherId = record[0];
int subjectId = record[1];
teacherToSubjects
.computeIfAbsent(teacherId, k -> new HashSet<>())
.add(subjectId);
}
List<int[]> result = new ArrayList<>();
for (Map.Entry<Integer, Set<Integer>> entry : teacherToSubjects.entrySet()) {
result.add(new int[] {entry.getKey(), entry.getValue().size()});
}
return result;
}
// Example usage
public static void main(String[] args) {
int[][] teacherRecords = {
{1, 2, 3},
{1, 2, 4},
{1, 3, 3},
{2, 1, 1},
{2, 2, 1},
{2, 3, 1},
{2, 4, 1}
};
List<int[]> results = countUniqueSubjects(teacherRecords);
for (int[] r : results) {
System.out.println("Teacher " + r[0] + " teaches " + r[1] + " unique subjects");
}
}
}// C++ solution
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
std::vector<std::pair<int, int>> countUniqueSubjects(const std::vector<std::tuple<int, int, int>>& teacherRecords) {
std::unordered_map<int, std::unordered_set<int>> teacherToSubjects;
for (const auto& record : teacherRecords) {
int teacherId = std::get<0>(record);
int subjectId = std::get<1>(record);
teacherToSubjects[teacherId].insert(subjectId);
}
std::vector<std::pair<int, int>> result;
for (const auto& entry : teacherToSubjects) {
result.emplace_back(entry.first, entry.second.size());
}
return result;
}
int main() {
std::vector<std::tuple<int, int, int>> teacherRecords = {
{1, 2, 3},
{1, 2, 4},
{1, 3, 3},
{2, 1, 1},
{2, 2, 1},
{2, 3, 1},
{2, 4, 1}
};
auto results = countUniqueSubjects(teacherRecords);
for (const auto& result : results) {
std::cout << "Teacher " << result.first << " teaches " << result.second << " unique subjects\n";
}
return 0;
}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.
Time Complexity: O(n) due to single-pass processing and set operations.
Space Complexity: O(m) corresponding to unique (teacher_id, subject_id) pairs.
Approach 3: Default Approach
# Write your MySQL query statement below
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY 1;Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using Hash Maps and Sets | Time Complexity: O(n), where n is the number of records in the input table, assuming average O(1) time complexity for set operations. |
| Approach 2: SQL-like Grouping and Aggregation | Time Complexity: O(n) due to single-pass processing and set operations. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Hash Map + Set Grouping | O(n) | O(n) | When processing rows in application code (Python/JS) without direct SQL aggregation |
| SQL GROUP BY with COUNT(DISTINCT) | O(n) | O(k) | Best for relational database queries where grouping and aggregation are supported |
Frequently asked questions
Is Number of Unique Subjects Taught by Each Teacher easy or hard?
The problem is classified as Easy because it relies on a single concept: counting distinct values per group. Once you recognize the grouping pattern, the solution is straightforward using either a hash map with sets or a SQL aggregation query.
Number of Unique Subjects Taught by Each Teacher Python/Java solution
Python solutions typically use a dictionary mapping teacher_id to a set of subject_id values, then return the set length for each teacher. Java or C++ solutions often mimic SQL-style grouping using maps and sets, while SQL implementations directly use GROUP BY teacher_id with COUNT(DISTINCT subject_id).
How to solve Number of Unique Subjects Taught by Each Teacher in O(n)?
Iterate through the records once and group subjects by teacher. Store subjects inside a set for each teacher using a hash map keyed by teacher_id. Insert subject_id into the set during iteration and finally return the size of each set. Because each row is processed once and set operations are O(1) on average, the total runtime is O(n).
What is the best approach for Number of Unique Subjects Taught by Each Teacher?
The most direct solution is grouping rows by teacher_id and counting distinct subject_id values. In SQL, this is implemented with GROUP BY teacher_id and COUNT(DISTINCT subject_id). In general programming languages, the equivalent approach uses a hash map where each teacher maps to a set of subjects, then the size of the set gives the answer.
Is Number of Unique Subjects Taught by Each Teacher asked at Google/Amazon/Meta?
This exact problem is primarily categorized as a database aggregation question similar to interview tasks seen at companies that evaluate SQL skills. Variants involving GROUP BY, COUNT, and DISTINCT frequently appear in interviews at companies like Amazon, Google, and data-focused roles.
What data structure is used in Number of Unique Subjects Taught by Each Teacher?
The typical in-memory solution uses a hash map combined with a set. The hash map groups rows by teacher_id, and the set ensures each subject_id is counted only once. In SQL implementations, the database internally performs similar grouping using hashing or sorting strategies.
What is the time complexity of Number of Unique Subjects Taught by Each Teacher?
The optimal solution runs in O(n) time where n is the number of rows in the table. Each row is processed once either during hash map insertion or during SQL grouping. Space complexity is O(n) in the hash map approach and about O(k) for SQL grouping where k is the number of unique teachers.
