Open In App

Minimum Increment operations to make Array unique

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
8 Likes
Like
Report

Given an array arr[] of integers. In one operation you can choose an index i, and increment the element arr[i] by 1. The task is to return the minimum number of operations needed to make every value in the array arr[] unique.
Examples

Input: arr[] = [3, 2, 1, 2, 1, 7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown that it is impossible for the array to have all unique values with 5 or less operations.

Input: arr[] = [1, 2, 2]
Output: 1
Explanation: After 1 operation [2 -> 3], the array could be [1, 2, 3].

Input: arr[] = [5, 4, 3, 2, 1]
Output: 0
Explanation: All elements are unique.

Expected Approach 1 - Use Sorting - O(n log(n)) Time and O(1) Space

The idea is to sort the array and then build a strictly increasing array by performing increment operations. Because elements in a strictly increasing array will always be unique.

Follow the given steps to solve the problem:

  • Sort the array in increasing order and initialize cnt to 0.
  • Starting from the second element, check if the current element is less than or equal to the previous element (Note that the previous element might become greater because of prior increment operations)
  • If the current element is less than or equal to the previous element, update current element = previous element + 1 to make it strictly increasing. Also, add the number of increments to cnt.

Illustration:


C++
C Java Python C# JavaScript

Output
6

 Expected Approach 2 - Use Frequency Array - O(n + max) Time and O(n + max) Space

The idea is to use a frequency array to count occurrences of each number in arr[], to make all elements unique. First, we create a sufficiently large frequency array based on the maximum element and size of array. Then, we iterate over this frequency array and check if the current number's frequency is greater than 1. If it is, we increment all extra occurrences by 1 to make the current number unique. This process continues until all numbers are unique. Also we will count these increment operations during the iteration.


C++
Java Python C# JavaScript

Output
5

Time Complexity: O(n + max), where n is the size of the array and max is its maximum element.
Auxiliary Space: O(n + max)


Minimum Increment operations to make Array unique
Visit Course explore course icon
Practice Tags :

Similar Reads