Minimum Increment to Make Array Unique — LeetCode 945 Python Solution
MediumGreedyArrayCountingSorting
- Problem
- #945
- Pattern
- Greedy
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(\log n) auxiliary |
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
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.