Minimum Increment to Make Array Unique - Problem
Minimum Increment to Make Array Unique
You are given an integer array
In each operation, you can pick any index
Example: If you have
Note: You can only increment values (never decrement), and the test cases guarantee the answer fits in a 32-bit integer.
You are given an integer array
nums that may contain duplicate values. Your goal is to make every element in the array unique by performing a series of increment operations.In each operation, you can pick any index
i where 0 <= i < nums.length and increment nums[i] by 1. You need to find the minimum number of moves required to make all values unique.Example: If you have
[3, 3, 3], you could transform it to [3, 4, 5] using 3 moves (0 + 1 + 2).Note: You can only increment values (never decrement), and the test cases guarantee the answer fits in a 32-bit integer.
Input & Output
example_1.py โ Basic duplicate removal
$
Input:
[1, 2, 2]
โบ
Output:
1
๐ก Note:
After sorting: [1, 2, 2]. The second 2 needs to be incremented to 3, requiring 1 move. Final array: [1, 2, 3]
example_2.py โ Multiple duplicates
$
Input:
[3, 3, 3]
โบ
Output:
3
๐ก Note:
After sorting: [3, 3, 3]. Second 3 becomes 4 (1 move), third 3 becomes 5 (2 moves). Total: 1 + 2 = 3 moves. Final array: [3, 4, 5]
example_3.py โ Already unique
$
Input:
[1, 3, 5, 7]
โบ
Output:
0
๐ก Note:
All elements are already unique, so no moves are needed. The array remains [1, 3, 5, 7]
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 105
- Important: You can only increment values, never decrement them
Visualization
Tap to expand
Understanding the Visualization
1
Sort Tickets
First, sort all ticket holders by their current seat numbers to process them systematically
2
Process in Order
Go through each person in order. If their seat is taken, assign them to the next available higher seat
3
Count Moves
Each seat reassignment counts as moves equal to the difference from original to new seat
Key Takeaway
๐ฏ Key Insight: Sorting first allows us to process duplicates in order, ensuring we always assign the smallest possible higher number to each duplicate, minimizing total moves.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code