




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.
1function minIncrementForUnique(nums) {
2    nums.sort((a, b) => a - b);
3    let moves = 0, need = nums[0];
4    for (const num of nums) {
5        moves += Math.max(0, need - num);
6        need = Math.max(need, num) + 1;
7    }
8    return moves;
9}
10
11const nums = [3,2,1,2,1,7];
12console.log(minIncrementForUnique(nums));This JavaScript code sorts the input array and calculates the minimal increments needed using a single loop post-sort, ensuring uniqueness.
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
Python's approach utilizes a large count array to record occurrences of each number. It processes this count array to ensure uniqueness by utilizing empty slots available, calculating the moves required effectively.