Algorithm
Problem Name: 945. Minimum Increment to Make Array Unique
Problem Link: https://leetcode.com/problems/minimum-increment-to-make-array-unique/
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.
The test cases are generated so that the answer fits in a 32-bit integer.
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 <= 105
0 <= nums[i] <= 105
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const minIncrementForUnique = function(nums) {
const seen = new Set()
const queue = []
let res = 0
for(const e of nums) {
if(!seen.has(e)) seen.add(e)
else queue.push(e)
}
queue.sort((a, b) => b - a)
for(let i = 0; i <= 1e5 || queue.length; i++) {
if(!seen.has(i) && i > last(queue)) {
res += i - queue.pop()
}
}
return res
function last(arr) {
return arr[arr.length - 1]
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def minIncrementForUnique(self, A):
st, used, move = set(A), set(), 0
heapq.heapify(A)
empty = [i for i in range(80000) if i not in st][::-1] if A else []
while A:
num = heapq.heappop(A)
if num not in used:
used.add(num)
else:
while empty[-1] < num:
empty.pop()
move += empty[-1] - num
heapq.heappush(A, empty.pop())
return move
Copy The Code &
Try With Live Editor
Input
Output