Minimum Increment to Make Array Unique - 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.

Return the minimum number of moves to make every value in nums unique.

The test cases are generated so that the answer fits in a 32-bit integer.

Input & Output

Example 1 — Basic Duplicates
$ Input: nums = [1,2,2]
Output: 1
💡 Note: One of the 2's needs to be incremented to 3. Total moves: 1 (change second 2 to 3).
Example 2 — Multiple Duplicates
$ Input: nums = [3,1,6,2,2,2]
Output: 3
💡 Note: After sorting: [1,2,2,2,3,6]. Second 2→3 (1 move), third 2→4 (2 moves). Total: 3 moves.
Example 3 — Already Unique
$ Input: nums = [1,2,3]
Output: 0
💡 Note: All elements are already unique, no moves needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Increment to Make Array Unique INPUT Integer Array nums 1 idx: 0 2 idx: 1 2 idx: 2 Duplicate found! nums = [1, 2, 2] length = 3 Goal: Make all values unique with min moves (1 move = increment by 1) ALGORITHM STEPS 1 Sort Array [1,2,2] is already sorted 2 Iterate Left to Right Compare adjacent elements 3 Fix Duplicates If nums[i] <= nums[i-1]: increment to nums[i-1]+1 4 Count Moves Add difference to total Process: i=1: 2 > 1 [OK] i=2: 2 <= 2 [FIX] 2 --> 3, moves += 1 FINAL RESULT Modified Array (Unique) 1 2 3 2 --> 3 (+1 move) OUTPUT 1 All values now unique! [1, 2, 3] - no duplicates Minimum moves: 1 [OK] Key Insight: Sorting first allows greedy processing - when we find a duplicate or smaller value, we only need to increment it to (previous + 1). This guarantees the minimum moves because we never "over-increment" and the array stays sorted throughout. TutorialsPoint - Minimum Increment to Make Array Unique | Optimal Solution (Sorting + Greedy)
Asked in
Google 15 Amazon 12 Meta 8 Apple 6
28.4K 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