Minimum Increment operations to make Array unique (original) (raw)

Last Updated : 02 Dec, 2024

Try it on GfG Practice redirect icon

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.

Table of Content

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:

**Illustration:

C++ `

// C++ Program to find minimum increment operations // to make array unique by sorting

#include #include #include using namespace std;

int minIncrements(vector& arr) {

  // sort the array in increasing order
  sort(arr.begin(), arr.end());

  int cnt = 0;
  for (int i = 1; i < arr.size(); i++) {
  
      // If current element <= the previous element
    if (arr[i] <= arr[i-1]) {
          
          // Make the array strictly increasing 
          // by updating current element to 
          // previous element + 1
          cnt += arr[i-1] + 1 - arr[i];
          arr[i] = arr[i-1] + 1;
    }
}

return cnt;

}

int main() { vector arr = {3, 2, 1, 2, 1, 7}; cout << minIncrements(arr); }

C

// C Program to find minimum increment operations // to make array unique by sorting #include <stdio.h> #include <stdlib.h>

// Comparator function for qsort int compare(const void *a, const void b) { return ((int *)a - *(int *)b); }

int minIncrements(int arr[], int n) {

// sort the array in increasing order
qsort(arr, n, sizeof(int), compare);

int cnt = 0;
for (int i = 1; i < n; i++) {
    
    // If current element <= the previous element
    if (arr[i] <= arr[i - 1]) {
        
        // Make the array strictly increasing 
        // by updating current element to 
        // previous element + 1;
        cnt += arr[i - 1] + 1 - arr[i];
        arr[i] = arr[i - 1] + 1;
    }
}

return cnt;

}

int main() { int arr[] = {3, 2, 1, 2, 1, 7}; int size = sizeof(arr) / sizeof(arr[0]);

printf("%d\n", minIncrements(arr, size));
return 0;

}

Java

// Java Program to find minimum increment operations // to make array unique by sorting import java.util.Arrays;

class GfG { static int minIncrements(int[] arr) {

    // sort the array in increasing order
    Arrays.sort(arr);
    
    int cnt = 0;
    for (int i = 1; i < arr.length; i++) {
        
        // If current element <= the previous element
        if (arr[i] <= arr[i - 1]) {
            
            // Make the array strictly increasing 
            // by updating current element to 
            // previous element + 1;
            cnt += arr[i - 1] + 1 - arr[i];
            arr[i] = arr[i - 1] + 1;
        }
    }
    
    return cnt;
}

public static void main(String[] args) {
    int[] arr = {3, 2, 1, 2, 1, 7};
    
    System.out.println(minIncrements(arr));
}

}

Python

Python Program to find minimum increment operations

to make array unique by sorting

def minIncrements(arr):

# sort the array in increasing order
arr.sort()

cnt = 0
for i in range(1, len(arr)):
    
    # If current element <= the previous element
    if arr[i] <= arr[i - 1]:
        
        # Make the array strictly increasing 
        # by updating current element to 
        # previous element + 1;
        cnt += arr[i - 1] + 1 - arr[i]
        arr[i] = arr[i - 1] + 1

return cnt

if name == "main": arr = [3, 2, 1, 2, 1, 7] print(minIncrements(arr))

C#

// C# Program to find minimum increment operations // to make array unique by sorting using System; using System.Collections.Generic;

class GfG { static int minIncrements(int[] arr) {

    // sort the array in increasing order
    Array.Sort(arr);
    
    int cnt = 0;
    for (int i = 1; i < arr.Length; i++) {
        
        // If current element <= the previous element
        if (arr[i] <= arr[i - 1]) {
            
            // Make the array strictly increasing 
            // by updating current element to 
            // previous element + 1;
            cnt += arr[i - 1] + 1 - arr[i];
            arr[i] = arr[i - 1] + 1;
        }
    }
    
    return cnt;
}

static void Main() {
    int[] arr = {3, 2, 1, 2, 1, 7};
    
    Console.WriteLine(minIncrements(arr));
}

}

JavaScript

// JavaScript Program to find minimum increment operations // to make array unique by sorting

function minIncrements(arr) {

// sort the array in increasing order
arr.sort((a, b) => a - b);

let cnt = 0;
for (let i = 1; i < arr.length; i++) {
    
    // If current element <= the previous element
    if (arr[i] <= arr[i - 1]) {
        
        // Make the array strictly increasing 
        // by updating current element to 
        // previous element + 1;
        cnt += arr[i - 1] + 1 - arr[i];
        arr[i] = arr[i - 1] + 1;
    }
}

return cnt;

}

// Driver Code let arr = [3, 2, 1, 2, 1, 7]; console.log(minIncrements(arr));

`

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++ `

// C++ Program to find the minimum increment operations // needed to make the array unique by using a frequency array

#include #include #include using namespace std;

int minIncrements(vector& arr) { int n = arr.size(); int cnt = 0;

// Find the maximum element in the array
int mx = *max_element(arr.begin(), arr.end());
vector<int> freq(n + mx, 0);

// Find the frequency of all elements from the array
for (int ele : arr) 
    freq[ele]++;
  
for (int num = 0; num < freq.size(); num++) {
    
    // If there is more than one occurrence of num
    if (freq[num] > 1) {
        
        // Increment all extra occurrences by 1 
        freq[num + 1] += freq[num] - 1;
        
        // Count these increment operations
        cnt += freq[num] - 1;
        freq[num] = 1;
    }
}

return cnt;

}

int main() { vector arr = {2, 1, 2, 4, 1};

cout << minIncrements(arr);

}

Java

// Java Program to find the minimum increment operations // needed to make the array unique by using a frequency array import java.util.Arrays;

class GfG { static int minIncrements(int[] arr) {

    int n = arr.length;
    int cnt = 0;

    // Find the maximum element in the array
    int mx = arr[0];
      for (int ele : arr) 
          mx = Math.max(mx, ele);
  
    int[] freq = new int[n + mx];

    // Find the frequency of all elements from the array
    for (int ele : arr)
        freq[ele]++;

    for (int num = 0; num < freq.length; num++) {
      
        // If there is more than one occurrence of num
        if (freq[num] > 1) {
          
            // Increment all extra occurrences by 1 
            freq[num + 1] += freq[num] - 1;

            // Count these increment operations
            cnt += freq[num] - 1;
            freq[num] = 1;
        }
    }

    return cnt;
}

public static void main(String[] args) {
    int[] arr = {2, 1, 2, 4, 1};
    System.out.println(minIncrements(arr));
}

}

Python

Python Program to find the minimum increment operations

needed to make the array unique by using a frequency array

def minIncrements(arr): n = len(arr) cnt = 0

# Find the maximum element in the array
mx = max(arr)
freq = [0] * (n + mx)

# Find the frequency of all elements from the array
for ele in arr:
    freq[ele] += 1

for num in range(len(freq)):
  
    # If there is more than one occurrence of num
    if freq[num] > 1:
      
        # Increment all extra occurrences by 1 
        freq[num + 1] += freq[num] - 1
        
        # Count these increment operations
        cnt += freq[num] - 1
        freq[num] = 1

return cnt

if name == "main": arr = [2, 1, 2, 4, 1] print(minIncrements(arr))

C#

// C# Program to find the minimum increment operations // needed to make the array unique by using a frequency array using System; class GfG { static int minIncrements(int[] arr) { int n = arr.Length; int cnt = 0;

    // Find the maximum element in the array
    int mx = arr[0];
    foreach (var ele in arr) {
        if (ele > mx) mx = ele;
    }

    int[] freq = new int[n + mx];

    // Find the frequency of all elements from the array
    foreach (var ele in arr) {
        freq[ele]++;
    }

    for (int num = 0; num < freq.Length; num++) {
      
        // If there are more than one occurrence of num
        if (freq[num] > 1) {
          
            // Increment all extra occurrences by 1 
            freq[num + 1] += freq[num] - 1;

            // Count these increment operations
            cnt += freq[num] - 1;
            freq[num] = 1;
        }
    }

    return cnt;
}

static void Main() {
    int[] arr = { 2, 1, 2, 4, 1 };
    Console.WriteLine(minIncrements(arr));
}

}

JavaScript

// JavaScript Program to find the minimum increment operations // needed to make the array unique by using a frequency array

function minIncrements(arr) { const n = arr.length; let cnt = 0;

// Find the maximum element in the array
const mx = Math.max(...arr);

const freq = new Array(n + mx).fill(0);

// Find the frequency of all elements from the array
arr.forEach(ele => {
    freq[ele]++;
});

for (let num = 0; num < freq.length; num++) {

    // If there is more than one occurrence of num
    if (freq[num] > 1) {
    
        // Increment all extra occurrences by 1 
        freq[num + 1] += freq[num] - 1;

        // Count these increment operations
        cnt += freq[num] - 1;
        freq[num] = 1;
    }
}

return cnt;

}

// Driver Code const arr = [2, 1, 2, 4, 1]; console.log(minIncrements(arr));

`

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