Problem
Table: Departments
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
In SQL, id is the primary key of this table.
The table has information about the id of each department of a university.
Table: Students
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
| department_id | int |
+---------------+---------+
In SQL, id is the primary key of this table.
The table has information about the id of each student at a university and the id of the department he/she studies at.
Find the id and the name of all students who are enrolled in departments that no longer exist.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 - SQL Anti-Join (NOT EXISTS)
Intuition
We want to find students whose department_id
does not exist in the Departments
table. This is a classic anti-join problem, solved with NOT EXISTS
or LEFT JOIN ... WHERE ... IS NULL
in SQL.
Approach
- For each student, check if their
department_id
is missing from theDepartments
table. - Return the student’s
id
andname
.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N + M)
where N = #students, M = #departments - 🧺 Space complexity:
O(N + M)