#945

Minimum Increment to Make Array Unique

Medium
ArrayGreedySortingCountingGreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting and a greedy approach to ensure each number is unique by only incrementing when necessary. This approach minimizes the number of increments by always ensuring the next number is greater than the last unique number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array to group duplicates together.
  2. 2Step 2: Initialize a variable to track the last unique number.
  3. 3Step 3: Iterate through the sorted array and for each number, if it is less than or equal to the last unique number, increment it to be one more than the last unique number and update the moves count.
solution.py12 lines
1# Full working Python code
2
3def minIncrementForUnique(nums):
4    nums.sort()
5    moves = 0
6    last_unique = -1
7    for num in nums:
8        if num <= last_unique:
9            moves += (last_unique + 1 - num)
10            num = last_unique + 1
11        last_unique = num
12    return moves

Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(1) because we are using a constant amount of extra space.

  • 1Sorting the array helps in grouping duplicates together, making it easier to handle them.
  • 2Using a greedy approach ensures that we only increment numbers when necessary, minimizing the total moves.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.