Problem
Table: Student
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| gender | varchar |
| dept_id | int |
+--------------+---------+
student_id is the primary key (column with unique values) for this table.
dept_id is a foreign key (reference column) to dept_id in the Department tables.
Each row of this table indicates the name of a student, their gender, and the id of their department.
Table: Department
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| dept_id | int |
| dept_name | varchar |
+-------------+---------+
dept_id is the primary key (column with unique values) for this table.
Each row of this table contains the id and the name of a department.
Write a solution to report the respective department name and number of students majoring in each department for all departments in the Department
table (even ones with no current students).
Return the result table ordered by student_number
in descending order. In case of a tie, order them by dept_name
alphabetically.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – SQL (LEFT JOIN and GROUP BY)
Intuition
To count the number of students in each department, including departments with zero students, we use a LEFT JOIN from Department to Student and group by department. This ensures all departments are included, even if no students are present.
Approach
- Use a LEFT JOIN from Department to Student on dept_id.
- GROUP BY dept_name to count students in each department.
- Use COUNT(student_id) to count students (NULL for departments with no students).
- ORDER BY student_number DESC, dept_name ASC.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m + k log k)
, where n is the number of students, m is the number of departments, and k is the number of departments (for sorting). - 🧺 Space complexity:
O(m + n)
, for the join and group by operations.