#1280
Students and Examinations
EasyDatabaseHash MapArray
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 leverages SQL's aggregation functions and joins to efficiently count the number of times each student attended each exam without the need for nested loops. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Use a LEFT JOIN to combine Students, Subjects, and Examinations tables.
- 2Step 2: Use COUNT() to aggregate the number of times each student attended each subject.
- 3Step 3: Group the results by student_id and subject_name, and order them accordingly.
solution.py7 lines
1# Full working Python code
2SELECT s.student_id, sub.subject_name, COUNT(e.student_id) AS attended
3FROM Students s
4CROSS JOIN Subjects sub
5LEFT JOIN Examinations e ON s.student_id = e.student_id AND sub.subject_name = e.subject_name
6GROUP BY s.student_id, sub.subject_name
7ORDER BY s.student_id, sub.subject_name;ℹ
Complexity note: The time complexity is O(n) because we are performing a single pass through the data with joins and aggregations. The space complexity is O(n) due to the storage of intermediate results in the result set.
- 1Understanding how joins work in SQL is crucial for efficient data retrieval.
- 2Using aggregation functions can simplify counting occurrences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.