KatInterview

Impute Missing Grades and Rank Top Candidates

Heaps, Sorting & SearchAuto-graded · 19 test cases
EasyAuto-gradedHeaps, Sorting & Searchsortingdata-cleaninghash-table

Last 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:

  1. Course-Level Imputation: Replace any missing score (None or NaN) 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.
  2. Student Performance Aggregation: For each student, compute their mean score across all record rows belonging to them, using the imputed values where necessary.
  3. 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.

Constraints

  • Input is a list of dictionaries, where each entry contains "student_id" (int), "subject" (str), and "score" (int, float, None, or float('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.