




Sponsored
This approach involves sorting the array first, and then iterating through it to ensure each element is greater than the previous. By keeping track of the necessary increments for each duplicate, we can ensure that every element in the array becomes unique.
Time Complexity: O(N log N) due to sorting and O(N) for linear traversal, resulting in O(N log N) overall.
Space Complexity: O(1) since no auxiliary space is used beyond input manipulation.
1#include <stdio.h>
2#include <stdlib.h>
3
4int cmp(const void *a, const void *b) {
5    return (*(int*)a - *(int*)b);
6}
7
8int minIncrementForUnique(int* nums, int numsSize) {
9    qsort(nums, numsSize, sizeof(int), cmp);
10    int moves = 0, need = nums[0];
11    for (int i = 0; i < numsSize; i++) {
12        moves += abs(need - nums[i]);
13        need = nums[i] + 1;
14    }
15    return moves;
16}
17
18int main() {
19    int nums[] = {3,2,1,2,1,7};
20    int size = sizeof(nums) / sizeof(nums[0]);
21    printf("%d\n", minIncrementForUnique(nums, size));
22    return 0;
23}First, we sort the array. We then iterate over the sorted array while tracking the next needed number to ensure uniqueness. For each element, we calculate the necessary moves by comparing it to the needed value, increment the moves counter accordingly, and then determine what the next needed unique value would be.
Instead of sorting, this method uses an array to count occurrences of each integer and then processes the count. For duplicate values, increments are calculated to fill gaps until all numbers are unique.
Time Complexity: O(N + M) where M is the range of numbers, due to counting and traversal.
Space Complexity: O(M) where M is the maximum possible number in nums.
1
JavaScript solution employs a counting array to manage the allocation of duplicate numbers into unique positions, aiming to achieve minimal moves with sequential logic over the count array.