MediumNo. 1112LeetCode Premium
Highest Grade For Each Student — LeetCode 1112 Python Solution
- Topics
- Database
- Reading time
- 4 min
- Source
- leetcode.com
Table schema
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
+---------------+---------+
| 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.