Skip to main content
holden

rank transform of an array

I was at a friend's bachelor party for the last ~week, so this is me getting back on the horse.

problem #

link

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

Input: arr = [40,10,20,30]
Output: [4,1,2,3]

Input: arr = [100,100,100]
Output: [1,1,1]

original solution #

  1. turn the array into a set to de-duplicate entries, and sort that
  2. use that set to make a mapping from int -> order (index + 1)
  3. return arr, where each element (key) is replaced by the order (value) from the map
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        sorted_set = sorted(set(arr))

        ranking = {i: index + 1 for index, i in enumerate(sorted_set)}

        return [ranking[i] for i in arr]

This one was simple, took about 2 minutes.


fixed solution #

None today. This one was easy.

81% speed, but the distribution is pretty normal. No distinct humps means the differences are micro optimizations.