Rank Transform of an Array

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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.
LeetCode Problem - 1331
class Solution {
public int[] arrayRankTransform(int[] arr) {
// Return early if the input array is empty
if (arr.length == 0) return arr;
// Use TreeSet to automatically sort and remove duplicates from the array
TreeSet<Integer> sortedSet = new TreeSet<>();
for (int num : arr) {
sortedSet.add(num); // Add each element to the sorted set
}
// Create a map to store the rank of each unique number in the array
Map<Integer, Integer> rankMap = new HashMap<>();
int rank = 1; // Start the rank from 1
for (int num : sortedSet) {
rankMap.put(num, rank++); // Assign the current rank and increment it
}
// Create a result array to store the rank of each number in the original array
int[] ans = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
ans[i] = rankMap.get(arr[i]); // Lookup the rank of each number in the rank map
}
// Return the array with transformed ranks
return ans;
}
}




