Minimum Increment to Make Array Unique — LeetCode 945 Python Solution

MediumGreedyArrayCountingSorting
Problem
#945
Pattern
Greedy
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview