1331. Rank Transform of an Array LeetCode Solution

In this guide, you will get 1331. Rank Transform of an Array LeetCode Solution with the best time and space complexity. The solution to Rank Transform of an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Rank Transform of an Array solution in C++
  4. Rank Transform of an Array solution in Java
  5. Rank Transform of an Array solution in Python
  6. Additional Resources
1331. Rank Transform of an Array LeetCode Solution image

Problem Statement of Rank Transform of an Array

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:

Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:

Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.

Example 3:

Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]

Constraints:

0 <= arr.length <= 105
-109 <= arr[i] <= 109

Complexity Analysis

  • Time Complexity: O(n\log n)
  • Space Complexity: O(n)

1331. Rank Transform of an Array LeetCode Solution in C++

class Solution {
 public:
  vector<int> arrayRankTransform(vector<int>& arr) {
    vector<int> sortedArr(arr);
    unordered_map<int, int> rank;

    ranges::sort(sortedArr);

    for (const int a : sortedArr)
      if (!rank.contains(a))
        rank[a] = rank.size() + 1;

    for (int& a : arr)
      a = rank[a];

    return arr;
  }
};
/* code provided by PROGIEZ */

1331. Rank Transform of an Array LeetCode Solution in Java

class Solution {
  public int[] arrayRankTransform(int[] arr) {
    int[] sortedArr = arr.clone();
    Map<Integer, Integer> rank = new HashMap<>();

    Arrays.sort(sortedArr);

    for (final int a : sortedArr)
      rank.putIfAbsent(a, rank.size() + 1);

    for (int i = 0; i < arr.length; ++i)
      arr[i] = rank.get(arr[i]);

    return arr;
  }
}
// code provided by PROGIEZ

1331. Rank Transform of an Array LeetCode Solution in Python

class Solution:
  def arrayRankTransform(self, arr: list[int]) -> list[int]:
    rank = {}

    for a in sorted(arr):
      if a not in rank:
        rank[a] = len(rank) + 1

    return map(rank.get, arr)
# code by PROGIEZ

Additional Resources

See also  374. Guess Number Higher or Lower LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.