Rank Transform of an Array

To solve this problem, follow these steps:

  1. First, make a copy of the array and sort it.
  2. Create a dictionary to keep track of the rank of each number. Initialize the rank to 1.
  3. Iterate over the sorted array. If the number is not in the dictionary, add it and its rank to the dictionary and increment the rank.
  4. Finally, replace each element in the original array with its rank from the dictionary.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        # Create a sorted list of unique elements in arr
        unique_arr = list(set(arr))
        unique_arr.sort()

        # Create an empty dictionary to map each number to its rank
        rank_dict = {}

        # Loop through the sorted array and assign ranks
        rank = 1
        for number in unique_arr:
            rank_dict[number] = rank
            rank += 1

        # Replace each number in arr with its rank
        result = []
        for number in arr:
            result.append(rank_dict[number])

        return result

In this code, sorted(set(arr)) creates a sorted list of unique elements in arr. {v: i + 1 for i, v in enumerate(sorted_arr)} maps each number to its rank. And [rank_dict[i] for i in arr] replaces each number in arr with its rank.