Problem
Table: Schools
+-------------+------+
| Column Name | Type |
+-------------+------+
| school_id | int |
| capacity | int |
+-------------+------+
school_id is the column with unique values for this table.
This table contains information about the capacity of some schools. The capacity is the maximum number of students the school can accept.
Table: Exam
+---------------+------+
| Column Name | Type |
+---------------+------+
| score | int |
| student_count | int |
+---------------+------+
score is the column with unique values for this table.
Each row in this table indicates that there are student_count students that got at least score points in the exam.
The data in this table will be logically correct, meaning a row recording a higher score will have the same or smaller student_count compared to a row recording a lower score. More formally, for every two rows i and j in the table, if scorei > scorej then student_counti <= student_countj.
Every year, each school announces a minimum score requirement that a student needs to apply to it. The school chooses the minimum score requirement based on the exam results of all the students:
- They want to ensure that even if every student meeting the requirement applies, the school can accept everyone.
- They also want to maximize the possible number of students that can apply.
- They must use a score that is in the
Exam
table.
Write a solution to report the minimum score requirement for each school.
If there are multiple score values satisfying the above conditions, choose the
smallest one. If the input data is not enough to determine the score, report -1
.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Join and Filter with Aggregation
Intuition
For each school, we want the highest possible number of applicants (student_count) that does not exceed the school’s capacity, and the smallest score that achieves this. If no such score exists, return -1.
Approach
- For MySQL/PostgreSQL:
- Join
Schools
andExam
on all rows (cross join). - For each school, filter exam scores where
student_count <= capacity
. - For each school, select the smallest score among those with the largest possible
student_count
(but not exceeding capacity). - If no such score exists, return -1 for that school.
- Join
- For Python (Pandas):
- For each school, filter exam rows where
student_count <= capacity
. - If no such row exists, assign -1.
- Otherwise, among the rows with the largest
student_count
, pick the smallest score.
- For each school, filter exam rows where
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(nm)
, where n is the number of schools and m is the number of exam scores, due to the cross-checking for each school. - 🧺 Space complexity:
O(n)
, for storing the result for each school.