Minimum Increment To Make Array Unique Problem
Description
LeetCode Problem 945.
You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
Example 1:
Input: nums = [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: nums = [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 with 5 or less moves that it is impossible for the array to have all unique values.
Constraints:
- 1 <= nums.length <= 10^5
- 0 <= nums[i] <= 10^5
Solution
Approach: Sort, Then Push Each Value Just Past the Previous One
Moves only increase values, so after sorting we can fix the array from left to right. Once the first i values are unique and increasing, the cheapest legal value for nums[i] is the smallest one that is not taken and not below its current value: max(nums[i], nums[i - 1] + 1).
- Sort
nums. - For each
ifrom1: ifnums[i] <= nums[i - 1], raise it tonums[i - 1] + 1and add the difference to the answer. Otherwise leave it, since it is already larger than everything before it.
Why sorting does not lose anything: which original number ends up on which final value does not change the total. The sum of the moves is always (sum of the final values) − (sum of the original values), so we only need the smallest possible set of distinct final values, and filling them greedily in sorted order gives exactly that.
The detail to get right is comparing with the updated previous value, not the original one. In [1,1,1], the second 1 becomes 2, and the third must become 3 (2 moves), not 2.
For nums = [3,2,1,2,1,7]: sorted it is [1,1,2,2,3,7], which becomes [1,2,3,4,5,7] with 1 + 1 + 2 + 2 = 6 moves.
Complexity: O(n log n) time for the sort and O(1) extra space besides the sort, where n is the length of nums.
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
nums.sort()
moves = 0
for i in range(1, len(nums)):
# Each value must be larger than the (already unique) value before it.
if nums[i] <= nums[i - 1]:
target = nums[i - 1] + 1
moves += target - nums[i]
nums[i] = target
return moves
Now write it from memory
Close the write-up and solve it yourself against the tests.