Rank Scores — LeetCode 178 Python Solution
MediumDatabase
- Problem
- #178
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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_dfComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
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.