Highest Grade For Each Student — LeetCode 1112 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1112
Reading time
4 min

Table schema

SQL
Table: Enrollments +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | course_id | int | | grade | int | +---------------+---------+ (student_id, course_id) is the primary key (combination of columns with unique values) of this table. grade is never NULL.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| course_id     | int     |
| grade         | int     |
+---------------+---------+
(student_id, course_id) is the primary key (combination of columns with unique values) of this table.
grade is never NULL.

Python solution

Python
import duckdb
import pandas as pd

def solution(enrollments: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Enrollments", enrollments)
    return con.execute("""WITH
    T AS (
        SELECT
            *,
            RANK() OVER (
                PARTITION BY student_id
                ORDER BY grade DESC, course_id
            ) AS rk
        FROM Enrollments
    )
SELECT student_id, course_id, grade
FROM T
WHERE rk = 1
ORDER BY student_id;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1112. Highest Grade For Each Student?
LeetCode 1112. Highest Grade For Each Student is rated Medium on LeetCode.
What topics does LeetCode 1112. Highest Grade For Each Student cover?
LeetCode 1112. Highest Grade For Each Student is tagged Database on LeetCode.
Is LeetCode 1112. Highest Grade For Each Student a premium problem?
Yes. LeetCode 1112. Highest Grade For Each Student is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview