315. Count of Smaller Numbers After Self
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Example 1:
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Example 2:
Input: nums = [-1]
Output: [0]
Example 3:
Input: nums = [-1,-1]
Output: [0,0]
Constraints:
- 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
- − 1 0 4 < = n u m s [ i ] < = 1 0 4 -10^4 <= nums[i] <= 10^4 −104<=nums[i]<=104
From: LeetCode
Link: 315. Count of Smaller Numbers After Self
Solution:
Ideas:
- Element Struct: Each element in the array is paired with its original index. This allows us to keep track of the position of each element even after sorting.
- mergeSort Function: Recursively splits the array into halves until we reach subarrays of size 1. Then, we merge these subarrays while counting how many smaller elements are to the right of each element.
- merge Function: During the merge step, we count how many elements from the right subarray are smaller than elements from the left subarray. This count is stored and used to update the counts array.
Code:
typedef struct {
int value;
int index;
} Element;
void merge(Element* elements, int* counts, int left, int mid, int right) {
int size = right - left + 1;
Element* temp = (Element*)malloc(size * sizeof(Element));
int i = left;
int j = mid + 1;
int k = 0;
int rightCount = 0;
while (i <= mid && j <= right) {
if (elements[i].value <= elements[j].value) {
counts[elements[i].index] += rightCount;
temp[k++] = elements[i++];
} else {
rightCount++;
temp[k++] = elements[j++];
}
}
while (i <= mid) {
counts[elements[i].index] += rightCount;
temp[k++] = elements[i++];
}
while (j <= right) {
temp[k++] = elements[j++];
}
for (i = left; i <= right; i++) {
elements[i] = temp[i - left];
}
free(temp);
}
void mergeSort(Element* elements, int* counts, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(elements, counts, left, mid);
mergeSort(elements, counts, mid + 1, right);
merge(elements, counts, left, mid, right);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countSmaller(int* nums, int numsSize, int* returnSize) {
*returnSize = numsSize;
int* counts = (int*)calloc(numsSize, sizeof(int));
Element* elements = (Element*)malloc(numsSize * sizeof(Element));
for (int i = 0; i < numsSize; i++) {
elements[i].value = nums[i];
elements[i].index = i;
}
mergeSort(elements, counts, 0, numsSize - 1);
free(elements);
return counts;
}