Minimum Increment to Make Array Unique - Problem
Minimum Increment to Make Array Unique

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
๐ŸŽญ Theater Seat Assignment AnalogyInitial Problem: Multiple people with same seatsP1Seat 3P2Seat 3P3Seat 3Step 1: Sort by seat number (already sorted)333Step 2: Assign seats greedily3โœ“ P1 keeps4P2: 3โ†’4 (1 move)5P3: 3โ†’5 (2 moves)Final Result: Total moves = 0 + 1 + 2 = 3Theater Layout345P1P2P3
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.
Asked in
Google 45 Amazon 32 Microsoft 28 Apple 15
24.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen