LeetCode: Relative Ranks Solution

Sometimes, LeetCode difficulty is not reliable

Approach: Sorting and Hash Table

(commented in implementation)

Implementation

1var findRelativeRanks = function (score) {
2 const [aBeforeB, bBeforeA] = [-1, 1] // for better readability when do sorting below
3
4 const positionRankMap = {
5 0: "Gold Medal",
6 1: "Silver Medal",
7 2: "Bronze Medal",
8 }
9
10 const indexRankMap = Object.fromEntries(
11 score
12 .map((s, i) => [s, i]) // create array of [score, index]
13 .sort(([sA], [sB]) => (sA > sB ? aBeforeB : bBeforeA)) // sort the array by score, descending
14 .map(([_, originalScoreIndex], index) => [
15 positionRankMap[index] || String(index + 1),
16 originalScoreIndex,
17 ]) // create array of [rank name, index in original score]
18 .map(([rank, originalScoreIndex]) => [originalScoreIndex, rank]) // to convert to object in the next step
19 )
20
21 return score.map((_, i) => indexRankMap[i])
22}

Comments

Loading comments...

Tags

leetcode

sorting

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Reverse Prefix of Word

Substring manipulating

Previous Post

LeetCode: Maximum Average Subarray I

Find maximum sum of contiguous subarray with length of K

HoningJS

Search Posts