Impute Missing Grades and Rank Top Candidates
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Process raw assessment records by replacing missing marks with course-level medians and return the top 5 performers.
You are given a log of student assessment entries, where each entry is represented as a dictionary containing three keys: "student_id" (an integer identifier), "subject" (a string course name), and "score" (a numerical mark, None, or float('nan')).
Your task is to calculate the overall mean performance for every student and identify the top 5 highest performers by applying the following data-processing rules:
- Course-Level Imputation: Replace any missing score (
NoneorNaN) with the median score of that specific subject, computed using only the existing valid scores for that course.- If a course has an odd number of valid scores $n$, the median is the value at index $n // 2$ of the sorted valid scores.
- If a course has an even number of valid scores $n$, the median is the mean of the values at indices $n // 2 - 1$ and $n // 2$ of the sorted valid scores.
- If a course has no valid scores at all, default its median score to
0.0.
- Student Performance Aggregation: For each student, compute their mean score across all record rows belonging to them, using the imputed values where necessary.
- Ranking & Output: Return a list of up to 5
"student_id"values representing the top performers ordered primarily by their mean score in descending order.- If two or more students have equal mean scores, break ties by ordering their
"student_id"values in ascending order. - If there are fewer than 5 unique students in the records, return all of them in ranked order.
- If two or more students have equal mean scores, break ties by ordering their
Constraints
- Input is a list of dictionaries, where each entry contains
"student_id"(int),"subject"(str), and"score"(int,float,None, orfloat('nan')). - $0 \le N \le 10^5$, where $N$ is the total number of records.
- Output must be a
List[int]containing at most 5 unique student IDs.
Examples
Example 1
Input: get_top_students([{'student_id': 1, 'subject': 'Math', 'score': 80}, {'student_id': 1, 'subject': 'Science', 'score': None}, {'student_id': 2, 'subject': 'Math', 'score': 90}, {'student_id': 2, 'subject': 'Science', 'score': 85}, {'student_id': 3, 'subject': 'Math', 'score': None}, {'student_id': 3, 'subject': 'Science', 'score': 70}])
Output: [2, 1, 3]
Hints
Hint 1
First, gather all valid non-null numerical scores for each subject and calculate each subject's median.
Hint 2
Next, iterate through all entries again to replace missing scores with their corresponding subject median and accumulate totals and counts for every student.
Hint 3
Finally, compute the average score per student and sort by primary key (-average) and secondary key (student_id). Take the first 5 elements.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires a two-phase data aggregation and imputation strategy:
-
Calculate Subject Medians:
- Collect all valid non-null numerical scores grouped by subject.
- For each subject, sort its list of valid scores.
- Calculate the median score. If the number of scores $n$ is odd, select the element at index $n // 2$. If even, take the average of the two middle elements at $n // 2 - 1$ and $n // 2$. If a subject has no valid recorded scores, assign its median as
0.0.
-
Impute and Aggregate Student Scores:
- Iterate through the records to fill missing entries (
NoneorNaN) using the calculated median for the corresponding subject. - Accumulate total score and total record count for each student.
- Iterate through the records to fill missing entries (
-
Rank and Extract Top Performers:
- Compute the mean score for each student ($\text{total_score} / \text{record_count}$).
- Sort all students by
(-mean_score, student_id)to rank by highest mean score first, and break ties with the loweststudent_id. - Return the top 5
student_idvalues from the sorted list.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N + S \log S)$, where $N$ is the total number of record rows and $S$ is the number of distinct students. Sorting scores per subject takes $\mathcal{O}(N \log N)$ total time across all subjects, and sorting the aggregated scores for all unique students takes $\mathcal{O}(S \log S)$.
- Space Complexity: $\mathcal{O}(N + S)$ auxiliary space to maintain subject score lists, row structures, and per-student cumulative totals.
Python Reference Solution
from collections import defaultdict
from typing import List, Dict
from math import isnan
def get_top_students(df_scores: List[Dict]) -> List[int]:
subject_scores = defaultdict(list)
students = set()
rows = []
for row in df_scores:
student_id = row['student_id']
subject = row['subject']
score = row['score']
students.add(student_id)
if score is not None and not (isinstance(score, float) and isnan(score)):
subject_scores[subject].append(float(score))
rows.append((student_id, subject, score))
medians = {}
for subject, scores in subject_scores.items():
scores.sort()
n = len(scores)
if n % 2:
medians[subject] = scores[n // 2]
else:
medians[subject] = (scores[n // 2 - 1] + scores[n // 2]) / 2.0
totals = defaultdict(float)
counts = defaultdict(int)
for student_id, subject, score in rows:
if score is None or (isinstance(score, float) and isnan(score)):
score = medians.get(subject, 0.0)
totals[student_id] += float(score)
counts[student_id] += 1
averages = [(totals[sid] / counts[sid], sid) for sid in students if counts[sid] > 0]
averages.sort(key=lambda item: (-item[0], item[1]))
return [sid for _, sid in averages[:5]]