MediumNo. 0178

Rank Scores — LeetCode 178 Python Solution

Topics
Database
Reading time
2 min

The problem

Rank every score from highest to lowest, giving tied scores the same rank and leaving no gap in the numbering after a tie, then return each score next to its rank ordered from highest score to lowest. The Scores table has id (int, primary key) and score (decimal with two places). The output columns are score and rank.

Example

Input
Scores(id, score) = (1, 3.51), (2, 3.65), (3, 4.05), (4, 3.85), (5, 4.05)
Output
(4.05, 1), (4.05, 1), (3.85, 2), (3.65, 3), (3.51, 4)
Explanation
The two 4.05 scores share rank 1 and the next distinct score is rank 2, because a tie consumes only one rank.

Python solution

PythonSolution
import pandas as pd


def order_scores(scores: pd.DataFrame) -> pd.DataFrame:
    # Use the rank method to assign ranks to the scores in descending order with no gaps
    scores["rank"] = scores["score"].rank(method="dense", ascending=False)

    # Drop id column & Sort the DataFrame by score in descending order
    result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False)

    return result_df

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0177Nth Highest SalaryMedium
0176Second Highest SalaryMedium
0180Consecutive NumbersMedium
0175Combine Two TablesEasy
0181Employees Earning More Than Their ManagersEasy
0182Duplicate EmailsEasy

Frequently asked questions

How hard is LeetCode 178. Rank Scores?

LeetCode 178. Rank Scores is rated Medium on LeetCode.

What topics does LeetCode 178. Rank Scores cover?

LeetCode 178. Rank Scores is tagged Database on LeetCode.

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.

Free to download. Check it runs on your machine, then pick a plan.