Highest Grade For Each Student — LeetCode 1112 Python Solution
MediumLeetCode PremiumDatabase
- Problem
- #1112
- Reading time
- 4 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(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.