Best-Scoring Enrollee for Each Academic Department
SQL & DataAuto-graded · 14 test casesLast updated
Pick one top student per department from two record lists, using GPA with deterministic tie-breaks, skipping missing values, and keeping departments that have no eligible student.
You are given two lists of records that mimic a small university database. Implement the logic that a "top row per group" SQL query with an outer join would perform, but in Python.
Input
departments: a list of dictionaries, each with the keysdept_id(int) anddept_name(str). Eachdept_idis unique.students: a list of dictionaries, each with the keys:student_id(int, unique)student_name(str)dept_id(int orNone)gpa(float orNone)enrolled_at(str, date inYYYY-MM-DDformat)
Task
For every department, find its single best student and report it.
A student is eligible only if both dept_id and gpa are not None. Ineligible students are ignored completely. A student whose dept_id matches no department is also never reported.
Among the eligible students of one department, the best student is chosen by this order:
- Highest
gpa. - If GPAs are equal, the earliest
enrolled_at(compare the date strings; theYYYY-MM-DDformat sorts chronologically). A missingenrolled_at(None) is treated as an empty string, so it counts as earliest. - If still tied, the smallest
student_id.
Output
Return a list of dictionaries, one per department, in the same order as the input departments list. Each dictionary has exactly these keys:
dept_id, dept_name, student_id, student_name, gpa, enrolled_at
- For a department with an eligible best student, the student fields are copied from that student.
- For a department with no eligible student, return a row with
student_id,student_name,gpaandenrolled_atall set toNone.
The dept_id and dept_name always come from the department record.
Constraints
- 0 <= len(departments), len(students) <= 10^5
dept_idvalues indepartmentsare unique;student_idvalues are unique.gpaisNoneor a number;dept_idof a student may beNone.enrolled_atstrings use theYYYY-MM-DDformat (or areNone).- The output must contain exactly one row per input department, in input order.
Examples
Example 1
Input: best_student_by_department([{'dept_id': 1, 'dept_name': 'CS'}, {'dept_id': 2, 'dept_name': 'Math'}, {'dept_id': 3, 'dept_name': 'Physics'}, {'dept_id': 4, 'dept_name': 'History'}], [{'student_id': 101, 'student_name': 'Alice', 'dept_id': 1, 'gpa': 3.9, 'enrolled_at': '2022-09-01'}, {'student_id': 102, 'student_name': 'Bob', 'dept_id': 1, 'gpa': 3.9, 'enrolled_at': '2023-01-15'}, {'student_id': 103, 'student_name': 'Cara', 'dept_id': 2, 'gpa': 3.85, 'enrolled_at': '2021-09-01'}, {'student_id': 104, 'student_name': 'Dan', 'dept_id': 2, 'gpa': None, 'enrolled_at': '2024-02-01'}, {'student_id': 105, 'student_name': 'Eve', 'dept_id': None, 'gpa': 3.7, 'enrolled_at': '2023-09-01'}, {'student_id': 106, 'student_name': 'Frank', 'dept_id': 3, 'gpa': 3.9, 'enrolled_at': '2020-09-01'}])
Output: [{'dept_id': 1, 'dept_name': 'CS', 'student_id': 101, 'student_name': 'Alice', 'gpa': 3.9, 'enrolled_at': '2022-09-01'}, {'dept_id': 2, 'dept_name': 'Math', 'student_id': 103, 'student_name': 'Cara', 'gpa': 3.85, 'enrolled_at': '2021-09-01'}, {'dept_id': 3, 'dept_name': 'Physics', 'student_id': 106, 'student_name': 'Frank', 'gpa': 3.9, 'enrolled_at': '2020-09-01'}, {'dept_id': 4, 'dept_name': 'History', 'student_id': None, 'student_name': None, 'gpa': None, 'enrolled_at': None}]
Hints
Hint 1
Students with a missing GPA or missing department can never win, so discard them before comparing anything.
Hint 2
You do not need to sort everything: scan the students once and keep, per department id, the best candidate seen so far using a comparison key.
Hint 3
Build the key as (negated gpa, enrolled_at or empty string, student_id) so that a smaller key means a better student; then walk the departments list and look up each id, producing None fields when there is no entry.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the "top row per group, keep empty groups" pattern, which in SQL would be a window function with a left join. In Python it reduces to a single pass plus a lookup.
- Scan the students once. Skip any student whose
dept_idorgpaisNone. - For each remaining student build a comparison key
(-gpa, enrolled_at or "", student_id). Negating the GPA turns "highest GPA first" into "smallest key first", and the remaining two parts handle the tie-breaks (earliest date, then smallest id). - Keep a dictionary from
dept_idto the best(key, student)seen so far, replacing the entry only when the new key is strictly smaller. - Walk the
departmentslist in its original order. For each one, look up its best student. If one exists copy its fields, otherwise fill the four student fields withNone.
Why it is correct
- Ineligible students are filtered up front, so a missing GPA can never win and a missing department never creates a row.
student_idis unique, so the key is a strict total order: exactly one student is minimal in each department, and the result does not depend on input order.- Iterating over
departments(not over the dictionary) guarantees one output row per department, in input order, including departments with no eligible students. - Students whose
dept_idmatches no department are stored in the dictionary but never looked up, so they never appear.
Complexity
- Time: O(S + D) for S students and D departments, since each student is compared once and each department is looked up once.
- Space: O(D') for the dictionary, where D' is the number of distinct department ids among eligible students (at most S).
Reference solution
from typing import Dict, List
def best_student_by_department(departments: List[Dict], students: List[Dict]) -> List[Dict]:
best_by_dept = {}
for student in students:
dept_id = student.get("dept_id")
gpa = student.get("gpa")
if dept_id is None or gpa is None:
continue
key = (-gpa, student.get("enrolled_at") or "", student["student_id"])
current = best_by_dept.get(dept_id)
if current is None or key < current[0]:
best_by_dept[dept_id] = (key, student)
result = []
for department in departments:
entry = best_by_dept.get(department["dept_id"])
student = entry[1] if entry else None
result.append({
"dept_id": department["dept_id"],
"dept_name": department["dept_name"],
"student_id": student["student_id"] if student else None,
"student_name": student["student_name"] if student else None,
"gpa": student["gpa"] if student else None,
"enrolled_at": student["enrolled_at"] if student else None,
})
return result