




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#include <vector>
#include <cmath>
using namespace std;
int minIncrementForUnique(vector<int>& nums) {
    int count[100000] = {0};
    for (int num : nums) count[num]++;
    int moves = 0, taken = 0;
    for (int i = 0; i < 100000; ++i) {
        if (count[i] > 1) {
            taken += count[i] - 1;
            moves -= i * (count[i] - 1);
        } else if (taken > 0 && count[i] == 0) {
            --taken;
            moves += i;
        }
    }
    return moves;
}
int main() {
    vector<int> nums = {3, 2, 1, 2, 1, 7};
    cout << minIncrementForUnique(nums) << endl;
    return 0;
}In this C++ solution, a counting array is used to determine how many times each number appears. We then manage excess numbers by replacing them into the next open positions, using a variable to track these replacements effectively.