Clean, Impute and Rank Student Score Records
Heaps, Sorting & SearchAuto-graded · 15 test casesLast updated
Filter records with too many missing values, fill gaps with per-subject medians, then pick the top five using a multi-key sort with tie-breaks.
You have a list of student records. Each record is a dictionary with these keys:
student_id: an integermath_score: a number, orNoneif missingenglish_score: a number, orNoneif missingphysics_score: a number, orNoneif missing
Write a function that cleans the records and returns the five best students. Follow these steps in this order:
- Discard sparse records. Remove every student who has
Nonein two or more of the three subjects. A student with exactly one missing subject stays. - Fill the gaps. For each subject, compute the median of that subject's non-missing values among the students who survived step 1. Replace each remaining
Nonein that subject with this median.- For an odd count of values, the median is the middle value of the sorted list.
- For an even count, it is the average of the two middle values.
- Rank. Sort the cleaned students by:
math_score, highest first;- then
physics_score, highest first; - then
student_id, lowest first.
- Select. Keep the first 5 students after sorting. If fewer than 5 remain, keep all of them.
Return the selected students as a list of dictionaries in ranked order. Each dictionary holds the full cleaned record with all four keys, so filled-in values appear in place of None. The input must not be modified.
Constraints
0 <= len(students) <= 10^5- Every record has all four keys. Missing scores are
None. - Medians are computed only after the sparse records are removed. Medians over the original list are not used.
- After step 2, every student has a numeric
math_scoreandphysics_score. A subject whose values are all missing among the survivors does not occur in the sort keys. - Duplicate
student_idvalues are not merged or removed. - If no students survive step 1, return an empty list.
Examples
Example 1
Input: rank_top_students([{'student_id': 1, 'math_score': 90, 'english_score': 80, 'physics_score': 85}, {'student_id': 2, 'math_score': None, 'english_score': 70, 'physics_score': 95}, {'student_id': 3, 'math_score': 75, 'english_score': None, 'physics_score': None}, {'student_id': 4, 'math_score': None, 'english_score': None, 'physics_score': 60}])
Output: [{'student_id': 2, 'math_score': 90, 'english_score': 70, 'physics_score': 95}, {'student_id': 1, 'math_score': 90, 'english_score': 80, 'physics_score': 85}]
Hints
Hint 1
Count the None values per record first and drop records with two or more. Do this before computing any statistic.
Hint 2
Compute each subject's median only from the surviving records, ignoring None. Sort the non-missing values and take the middle, averaging the two middle values when the count is even.
Hint 3
Copy the records before filling gaps so the input is untouched. Use a sort key of (-math_score, -physics_score, student_id), then slice the first 5.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a short pipeline, and the order of the steps determines the answer.
- Filter. Count the
Nonevalues in each record and keep only records with fewer than two. We copy each kept record so the caller's data is never changed. - Impute. For each subject, collect the non-missing values from the surviving records, sort them, and take the median. Use the middle element for an odd count, or the mean of the two middle elements for an even count. Then replace every
Nonein that subject with the median. - Sort. Use the key
(-math_score, -physics_score, student_id). Negating the scores gives descending order for them, whilestudent_idstays ascending. This makes the order fully deterministic. - Slice.
kept[:5]returns up to five records and handles lists shorter than five without special cases.
Why it is correct
- Medians are computed after filtering, as the task requires. Computing them earlier would include students who are later discarded and could change the filled values.
- Imputation happens before sorting, so the sort keys are always numbers.
- The three-part sort key encodes exactly the stated priority: math, then physics, then ID.
- Slicing a list never fails when it is shorter than 5.
- An empty input, or an input where everyone is filtered out, gives an empty list.
Complexity
Let n be the number of students.
- Time: O(n log n). Sorting dominates, and the three median computations also sort, which is O(n log n) each.
- Space: O(n) for the copied records and the sorted value lists.
Reference solution
from typing import Dict, List, Optional
def rank_top_students(records):
subjects = ("math_score", "english_score", "physics_score")
# Step 1: keep only students with at most one missing subject (copy them).
kept = [
dict(rec)
for rec in records
if sum(rec.get(s) is None for s in subjects) < 2
]
# Step 2: per-subject median over survivors, then fill.
for subject in subjects:
values = sorted(
rec[subject] for rec in kept if rec.get(subject) is not None
)
if not values:
continue
mid = len(values) // 2
if len(values) % 2:
median = values[mid]
else:
median = (values[mid - 1] + values[mid]) / 2
for rec in kept:
if rec.get(subject) is None:
rec[subject] = median
# Step 3: multi-key sort.
kept.sort(key=lambda rec: (
-rec["math_score"],
-rec["physics_score"],
rec["student_id"],
))
# Step 4: top five.
return kept[:5]