Replace Elements by Rank

Medium Problems DSA practice problem on Onlearn.

Difficulty: easy.

Topics: Replace elements by their rank in the array, Sorting, Map, Arrays, Hashing, Time Complexity, Space Complexity, complexity analysis, sorting algorithms, hashing, array manipulation, set, Hashing & Hash Maps, Sets & Hash Sets.

Problem Statement Given an array of integers, replace each element of the array with its rank. The rank of an element is defined as follows: 1. The rank starts from 1. 2. The smallest element in the array has Rank 1. 3. The second smallest element has Rank 2, and so on. 4. If two elements are equal, they must have the same rank. 5. The rank increases only when the element value increases. For example, if the input array is [100, 2, 70, 2], the sorted unique elements are 2, 70, 100. Therefore, 2 gets Rank 1, 70 gets Rank 2, and 100 gets Rank 3. The output array should be [3, 1, 2, 1]. Input Specification The first line contains an integer N , representing the size of the array. The second line contains N space separated integers representing the elements of the array. Output Specification Print a single line containing N space separated integers where each integer represents the rank of the corresponding element in the input array. Constraints 1 ≤ N ≤ 10^5 10^9 ≤ Array elements ≤ 10^9 Sample Test Cases Sample Input 1 Sample Output 1 Explanation: The sorted order of elements is: 2, 6, 15, 20, 26, 98. Ranks are: 2 1 6 2 15 3 20 4 26 5 98 6 Replacing original elements with ranks: [4, 3, 5, 1, 6, 2]. Sample Input 2 Sample Output 2 Explanation: All elements are equal. The smallest (and only) element is 10, so it gets Rank 1. Sample Input 3 Sample Output 3 Explanation: Sorted unique elements: 10, 20, 30, 40. Ranks: 10 1, 20 2, 30 3, 40 4. Note that both instances of 10 receive Rank 1. Difficulty Level Easy