Problem 506

Abstract / Summary

Assign ranks to scores where first gets Gold, second Silver, third Bronze, and others get their numeric rank.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0506.py

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        places = sorted(score)

        for s in score:
            pos = len(score) - bisect_left(places, s)
            if pos == 1:
                yield "Gold Medal"
            elif pos == 2:
                yield "Silver Medal"
            elif pos == 3:
                yield "Bronze Medal"
            else:
                yield str(pos)
14 lines | 441 bytes | submitted September 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 75% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Heap (Priority Queue)
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that receives a list of integer scores and produces a list of rank descriptors. The highest score receives “Gold Medal”, the second highest “Silver Medal”, the third “Bronze Medal”, and all remaining scores receive their numeric rank as a string. The method uses sorting, binary search, and a generator to construct the output.

Key Steps

Sorting the scores

The first operation creates a sorted copy of the input scores in ascending order.

places = sorted(score)

By keeping a separate sorted collection, the original ordering of the input is preserved for later rank lookup while enabling efficient position queries.

Determining the rank position

For each original score the code computes its rank by locating the leftmost occurrence of that score in the sorted list and converting the index to a 1-based rank measured from the highest score.

pos = len(score) - bisect_left(places, s)

bisect_left performs a binary search, returning the index of the first element that is not less than the target. Subtracting this index from the total number of scores yields the rank where the largest score maps to position 1.

Mapping rank to output string

A series of conditional checks translate the numeric rank into the appropriate textual representation.

if pos == 1:
    yield "Gold Medal"
elif pos == 2:
    yield "Silver Medal"
elif pos == 3:
    yield "Bronze Medal"
else:
    yield str(pos)

The use of yield turns the method into a generator, emitting each rank descriptor in the order of the original scores.

Edge Cases Handled

When multiple participants share the same score, bisect_left returns the index of the first occurrence in the sorted list. Consequently, all equal scores receive the same rank because the calculation subtracts the same index from the total length. This behavior ensures that ties are reflected consistently in the output.

The conditional block explicitly covers the first three positions, guaranteeing that the special medal strings are produced even when the input contains fewer than three participants. For inputs with fewer than three scores, the corresponding if or elif branches still match the existing positions, and the else clause handles any remaining ranks.

The generator approach naturally accommodates an empty input list. In that scenario the for loop does not execute, and the method yields no values, resulting in an empty list when the generator is consumed.

Performance Optimizations

Sorting the scores once provides an ordered reference that enables rapid rank lookup for each element. By employing bisect_left, each rank determination executes a binary search, which scales logarithmically with the number of scores. This avoids the need for a nested scan of the list for every element, reducing the overall work compared to a naïve double-loop approach.

The use of a generator (yield) defers the creation of the result list until it is iterated. This lazy production means that memory is allocated only for the current output string rather than for an entire intermediate list, which can be advantageous when the caller consumes the results incrementally or when the input size is large.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of friends who just finished a race. Each friend has a score, and the goal is to give them a prize based on how high their score is compared to the others. First, the code lines up all the scores from smallest to largest to see who did the best. Then, it looks at each person's score one by one to see where they fit in that line. If a person has the highest score, they get a gold medal. If they have the second highest, they get a silver medal, and if they have the third highest, they get a bronze medal. For everyone else who didn't win one of the top three prizes, the code just tells them what number they earned in the race, like fourth or fifth place. It moves through the list until every person has their award.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.78 | σ = 1.85

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
36 links | 24 authors | 10 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 easy 6 medium
12 solutions   September 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality