LeetCode 1331: Rank Transform of an Array Solution

Master LeetCode problem 1331 (Rank Transform of an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1331. Rank Transform of an Array

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Create a copy of the input array and sort it to get the ranks.
  2. Create a map to store the mapping of element to rank.
  3. Iterate through the sorted array, assigning ranks to elements based on their position in the sorted array.
  4. Finally, retrieve the ranks for the original array elements from the map.

Time complexity: O(n log n) where n is the number of elements in the input array due to sorting.
Space complexity: O(n) for the map and the sorted array copy.

Solution Code

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] arrayRankTransform(int[] arr) {
        int[] sortedArr = arr.clone();
        Arrays.sort(sortedArr);
        
        Map<Integer, Integer> rankMap = new HashMap<>();
        int rank = 1;
        for (int num : sortedArr) {
            if (!rankMap.containsKey(num)) {
                rankMap.put(num, rank);
                rank++;
            }
        }
        
        int[] result = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            result[i] = rankMap.get(arr[i]);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1331 (Rank Transform of an Array)?

This page provides optimized solutions for LeetCode problem 1331 (Rank Transform of an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1331 (Rank Transform of an Array)?

The time complexity for LeetCode 1331 (Rank Transform of an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1331 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1331 in Java, C++, or Python.

Back to LeetCode Solutions