Domain 2MediumMEDIUM

Highest Grade For Each Student

Uses pandas inner join and groupby to efficiently calculate maximum scores per student while handling missing exam records via filtering.

Domain: medium•Updated: 2026-09-08
#pandas merge#groupby aggregation#O(n)#inner join

Problem Breakdown

We are given two DataFrames: students (containing unique identifiers and names) and examinations (recording scores). The objective is to compute the highest score for each student. We must handle students who have taken exams, ensuring that those without any exam records do not appear in the result set based on the problem constraints provided.

Intuition

A naive approach would iterate through every row manually or use nested loops (O(N×M)O(N \times M)), which is inefficient for large datasets. Pandas provides vectorized operations like merge and groupby. By joining the tables, we align student names with their exam scores. Using inner join, we automatically filter out students without exams (since they have no matching rows in examinations). Grouping by unique identifiers allows us to aggregate multiple score records into a single maximum value per student efficiently using built-in C-accelerated functions.

Approach

  1. Merge: Perform an inner merge between students and examinations on the common key student_id. This ensures we only process students who have at least one exam record, satisfying the constraint to exclude students without grades.
  2. Group By & Aggregate: Group the merged data by unique student identifiers (student_id, name) and apply .max() on the score column. Including name in the group key handles potential duplicate names across different IDs correctly.
  3. Format Output: Rename the aggregated score column to match the required output schema (highest_grade). Sort the result by student_id to ensure deterministic ordering, which is often expected by automated judges for Pandas problems.

Complexity Analysis

  • Time Complexity: O(N)O(N), where NN is the number of rows in the merged dataset (total exam records). The merge operation and subsequent groupby aggregation are linear with respect to input size assuming hash-based indexing used internally by pandas. Sorting adds a logarithmic factor relative to unique students (Klog⁡KK \log K), but this remains efficient for typical constraints.
  • Space Complexity: O(N)O(N) auxiliary space, where NN is the number of rows in the merged DataFrame before aggregation. This accounts for storing intermediate data during the join and groupby operations (excluding output storage).

Solution

import pandas as pd

def highest_grade_for_each_student(students: pd.DataFrame, examinations: pd.DataFrame) -> pd.DataFrame:
    """
    Finds each student's highest score from all of their exams.
    
    Args:
        students: DataFrame with columns ['student_id', 'name']
        examinations: DataFrame with columns ['student_id', 'exam_name', 'score']
        
    Returns:
        DataFrame with columns ['student_id', 'name', 'highest_grade'], sorted by student_id.
    """
    # 1. Join Students and Examinations to ensure we have names for students who took exams.
    # Using inner join filters out students without any exam records (no grade exists).
    merged_df = pd.merge(students, examinations, on='student_id', how='inner')

    # 2. Group by student identity and aggregate the maximum score per group.
    result = merged_df.groupby(['student_id', 'name'], as_index=False)['score'].max()

    # 3. Rename column to match expected output format exactly.
    result.rename(columns={'score': 'highest_grade'}, inplace=True)

    # Sort by student_id for deterministic ordering (standard practice in LeetCode Pandas problems).
    return result.sort_values('student_id')

Edge Cases Handled

  • Students with No Exams: The inner join automatically excludes students who have no corresponding rows in the examinations table, preventing NULL values for grades which would be invalid per problem constraints.
  • Multiple Exam Rows per Student: The groupby(...).max() logic correctly collapses multiple exam records into a single row representing their highest score.
  • Non-Unique Names: By grouping on both student_id and name, we ensure that if two students share the same name, they are treated as distinct entities based on their unique ID.
  • Output Ordering: The solution explicitly sorts by student_id to guarantee consistent output order across different execution environments or test cases.