Sponsored
Sponsored
This approach involves sorting the array to determine the rank of each element. After sorting, unique elements are mapped to their ranks.
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the sorted array and rank map.
1#include <stdio.h>
2#include <stdlib.h>
3
4int cmpfunc (const void * a, const void * b) {
5 return ( *(int*)a - *(int*)b );
6}
7
8int* arrayRankTransform(int* arr, int arrSize, int* returnSize) {
9 *returnSize = arrSize;
10 if (arrSize == 0) return NULL;
11
12 int* sorted = (int*)malloc(arrSize * sizeof(int));
13 for (int i = 0; i < arrSize; i++) sorted[i] = arr[i];
14 qsort(sorted, arrSize, sizeof(int), cmpfunc);
15
16 int* rankMap = (int*)malloc(arrSize * sizeof(int));
17 int rank = 1;
18 rankMap[0] = sorted[0];
19 int rankArr[1] = {rank};
20
21 for (int i = 1; i < arrSize; i++) {
22 if (sorted[i] != sorted[i - 1]) {
23 rank++;
24 }
25 rankArr[rank] = sorted[i];
26 }
27
28 int* result = (int*)malloc(arrSize * sizeof(int));
29 for (int i = 0; i < arrSize; i++) {
30 for (int j = 0; j < rank; j++) {
31 if (arr[i] == rankMap[j]) {
32 result[i] = j + 1;
33 break;
34 }
35 }
36 }
37
38 free(sorted);
39 free(rankMap);
40 return result;
41}
The C solution involves sorting the array and creating a map of ranks. Sorted unique elements are assigned ranks incrementally. The original elements are then mapped to their ranks using this mapping.
Coordinate compression is a method to map large ranges of numbers to smaller ranges, maintaining their relative order. This approach uses this idea to assign ranks.
Time Complexity: O(N log N) due to sorting and binary search operations.
Space Complexity: O(N) for rank maps.
1def arrayRankTransform(arr):
2 sorted_arr =
Coordinate compression in this Python solution involves using sorting and a dictionary for mapping ranks. The sorted elements guide the rank allocation to the array with minimal memory use.