Hone logo
Hone
Problems

Rank Scores

You are given a table of scores, and you need to assign a rank to each score. The ranking should follow standard rules where identical scores receive the same rank, and the next rank is skipped. This is a common task in data analysis and leaderboard systems where you need to order participants based on their performance.

Problem Description

Given a table named Scores with a single column score representing individual scores, you need to produce a result table that displays each score along with its corresponding rank.

The ranking rules are as follows:

  1. Scores should be ranked in descending order (highest score gets rank 1).
  2. If two or more players have the same score, they should receive the same rank.
  3. The rank assigned should be the dense rank. This means that if multiple scores share a rank, the next rank assigned should be the immediately following integer. For example, if scores of 100, 100, and 90 are present, the ranks would be 1, 1, and 2, respectively (not 1, 1, and 3).

The output should be a table with two columns: score and rank.

Examples

Example 1:

Input Table: Scores
| score |
|-------|
| 3.50  |
| 3.50  |
| 3.65  |
| 4.00  |
| 3.85  |
| 3.85  |

Output Table:
| score | rank |
|-------|------|
| 4.00  | 1    |
| 3.85  | 2    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.50  | 4    |
| 3.50  | 4    |

Explanation:
- 4.00 is the highest score, so it gets rank 1.
- 3.85 is the next highest unique score, so it gets rank 2. Both occurrences of 3.85 get rank 2.
- 3.65 is the next highest unique score, so it gets rank 3.
- 3.50 is the next highest unique score, so it gets rank 4. Both occurrences of 3.50 get rank 4.

Example 2:

Input Table: Scores
| score |
|-------|
| 50    |
| 75    |
| 100   |

Output Table:
| score | rank |
|-------|------|
| 100   | 1    |
| 75    | 2    |
| 50    | 3    |

Explanation:
All scores are unique and in descending order, so they receive consecutive ranks starting from 1.

Example 3:

Input Table: Scores
| score |
|-------|
| 100   |
| 100   |
| 100   |

Output Table:
| score | rank |
|-------|------|
| 100   | 1    |
| 100   | 1    |
| 100   | 1    |

Explanation:
All scores are identical, so they all receive the same rank (1).

Constraints

  • The Scores table will contain at least one row.
  • The score column will contain numerical values.
  • Scores can be integers or floating-point numbers.
  • The maximum number of rows in the Scores table is $10^5$.
  • The values in the score column will be between 0.00 and 100.00, inclusive.

Notes

  • You will need to consider how to handle duplicate scores correctly.
  • Think about the order in which scores should be processed.
  • This problem is a good exercise in using window functions or analytical functions in SQL, or equivalent concepts in other programming languages.
Loading editor...
plaintext