945. Minimum Increment to Make Array Unique
Tapan Rachchh
1 min read
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
nums.sort()
ans = 0
for i in range(len(nums) - 1):
if nums[i] >= nums[i + 1]:
ans += 1 + (nums[i] - nums[i + 1])
nums[i + 1] = nums[i] + 1
return ans
Using counting sort
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
maxVal = 0
minVal = float('inf')
c = defaultdict(int)
ans = 0
for e in nums:
minVal = min(minVal, e)
maxVal = max(maxVal, e)
c[e] += 1
i = minVal
while i <= maxVal:
if c[i] > 1:
x = c[i] - 1
ans += x
c[i + 1] += x
maxVal = max(maxVal, i + 1)
i += 1
return ans
0
Subscribe to my newsletter
Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by