MediumNo. 0945
Minimum Increment to Make Array Unique — LeetCode 945 Python Solution
- Pattern
- Greedy
- Topics
- Greedy, Array, Counting, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [1,2,2]
- Output
- 1
- Explanation
- After 1 move, the array could be [1, 2, 3].
Python solution
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
nums.sort()
ans, y = 0, -1
for x in nums:
y = max(y + 1, x)
ans += y - x
return ansComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(log n)
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 945. Minimum Increment to Make Array Unique is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0948 | Bag of Tokens | Medium |
| 0179 | Largest Number | Medium |
| 0324 | Wiggle Sort II | Medium |
| 0452 | Minimum Number of Arrows to Burst Balloons | Medium |
| 0455 | Assign Cookies | Easy |
| 0502 | IPO | Hard |
Frequently asked questions
- How hard is LeetCode 945. Minimum Increment to Make Array Unique?
LeetCode 945. Minimum Increment to Make Array Unique is rated Medium on LeetCode.
- What is the time complexity of LeetCode 945. Minimum Increment to Make Array Unique?
The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 945. Minimum Increment to Make Array Unique?
The Python solution on this page uses O(log n) auxiliary space.
- What topics does LeetCode 945. Minimum Increment to Make Array Unique cover?
LeetCode 945. Minimum Increment to Make Array Unique is tagged Greedy, Array, Counting and Sorting on LeetCode.