Given an array A of integers. In one move you can choose any element A[i], and increment it by 1. The task is to return the minimum number of moves needed to make every value in the array A unique.
Input: A = [3, 2, 1, 2, 1, 7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown that it is impossible for the array to have all unique values with 5 or less moves. Input: A = [1, 2, 2] Output: 1 Explanation: After 1 move [2 -> 3], the array could be [1, 2, 3].
A simple solution to make each duplicate values unique is to keep incrementing it repeatedly until it is not unique. However, we might do a lot of extra work, if we have an array of all ones.
So, what we can do instead is to evaluate what our increments should be. If for example we have [1, 1, 1, 3, 5], we don’t need to process all the increments of duplicated 1’s. We could take two ones (taken = [1, 1]) and continue processing. Whenever we find an empty(unused value) place like 2 or 4 we can then recover that our increment will be 2-1, 4-1 respectively.
Thus, we first count the values and for each possible value X in array:
- If there are 2 or more values X in A, save the extra duplicated values to increment later.
- If there are 0 values X in A, then a saved value gets incremented to X.
Below is the implementation of above approach:
Time Complexity: O(N)
- Minimum increment operations to make the array in increasing order
- Minimum number of increment-other operations to make all array elements equal.
- Minimum increment or decrement operations required to make the array sorted
- Minimum increment by k operations to make all elements equal
- Minimum increment/decrement operations required to make Median as X
- Minimum range increment operations to Sort an array
- Minimum number of increment/decrement operations such that array contains all elements from 1 to N
- Minimum Increment / decrement to make array elements equal
- Minimum operations to make XOR of array zero
- Minimum gcd operations to make all array elements one
- Minimum operations to make GCD of array a multiple of k
- Minimum operations to make counts of remainders same in an array
- Make all the array elements odd with minimum operations of given type
- Minimum no. of operations required to make all Array Elements Zero
- Minimum number of operations on an array to make all elements 0
- Minimum operations to make all elements equal using the second array
- Minimum delete operations to make all elements of array same
- Minimum operations required to make all Array elements divisible by K
- Minimum Cost to make all array elements equal using given operations
- Minimum pair sum operations to make array each element divisible by 4