




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
class Solution {
    public int MinIncrementForUnique(int[] nums) {
        int[] count = new int[100000];
        foreach (var num in 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;
    }
    static void Main() {
        var nums = new int[]{3, 2, 1, 2, 1, 7};
        var sol = new Solution();
        Console.WriteLine(sol.MinIncrementForUnique(nums));
    }
}The C# solution is similar, utilizing an integer array to count occurrences. It processes this information to distribute duplicated values into open, unique slots efficiently.