↓Skip to main content
  1. LeetCode/

LeetCode 506: Relative Ranks

·1 min· ·
LeetCode Easy Array Sorting Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted ×2

Approach
#

Sort indices by score from high to low (or pop them from a max-heap, Heap); rank r (0-based) gets Gold Medal, Silver Medal or Bronze Medal for the top three and str(r + 1) otherwise, written back at the original index.

My Solution
#

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        res = [""] * len(score)
        order = sorted(range(len(score)), key=lambda i: -score[i])
        for r, i in enumerate(order):
            res[i] = medals[r] if r < 3 else str(r + 1)
        return res

Complexity
#

Time O(n log n), space O(n).

Mistakes to Avoid
#

  • Write each result at its original position, not in sorted order.

Interview Explanation
#

I sort indices by score descending and write medals or rank strings back at the original indices. Time O(n log n).

Related

LeetCode 414: Third Maximum Number
·1 min
LeetCode Easy Array Sorting
LeetCode 414 note: track the three largest distinct values, skipping repeats, and return the maximum if fewer than three distinct values exist
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 485: Max Consecutive Ones
·1 min
LeetCode Easy Array
LeetCode 485 note: extend the current count on a 1, reset it on a 0, and keep the maximum