Leetcode 1331. Rank Transform of an Array
Given an array of integers arr
, you will need to transform the array such that each element of the array will be replaced by its rank.
The rank represents how large the element is. The rank has the following rules:
Q: Are there any constraints on the size of the array? A: There is no specific constraint mentioned for the size of the array, but typically problems on LeetCode fit within reasonable memory and performance limits.
Q: Can the array contain negative numbers? A: Yes, the array can contain negative numbers as there are no restrictions mentioned regarding the range of numbers.
Q: What should be done if the array is empty? A: If the array is empty, we should return an empty array as there are no elements to rank.
import java.util.Arrays;
import java.util.HashMap;
public class Solution {
public int[] arrayRankTransform(int[] arr) {
if (arr == null || arr.length == 0) {
return new int[0];
}
int[] sortedArr = arr.clone();
Arrays.sort(sortedArr);
HashMap<Integer, Integer> rankMap = new HashMap<>();
int rank = 1;
for (int num : sortedArr) {
if (!rankMap.containsKey(num)) {
rankMap.put(num, rank++);
}
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = rankMap.get(arr[i]);
}
return result;
}
}
Hence, the overall time complexity of the solution is (O(n \log n)).
This effectively solves the problem by ensuring all elements are ranked correctly based on their unique values and their respective sorted positions.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?