Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Distinct adjacent elements in a binary array
Next article icon

Minimum Increment operations to make Array unique

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
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
  •  Expected Approach 2 – Use Frequency Array – O(n + max) Time and O(n + max) Space

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++ Program to find minimum increment operations // to make array unique by sorting  #include <iostream> #include <vector> #include <algorithm> using namespace std;  int minIncrements(vector<int>& 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<int> 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)); 

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++
// C++ Program to find the minimum increment operations // needed to make the array unique by using a frequency array  #include <iostream> #include <vector> #include <algorithm> using namespace std;  int minIncrements(vector<int>& 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<int> 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)); 

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)



Next Article
Distinct adjacent elements in a binary array

S

Sanjit_Prasad
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Python Programs
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Distinct adjacent elements in a binary array
    Given a binary array arr[] of 1's and 0's of length N. The task is to find the number of elements that are different with respect to their neighbors. Note: At least one of the neighbors should be distinct. Examples: Input : N = 4 , arr=[1, 0, 1, 1] Output : 3 arr[0]=1 is distinct since it's neighbor
    5 min read
  • Smallest element present in every subarray of all possible lengths
    Given an array arr[] of length N, the task for every possible length of subarray is to find the smallest element present in every subarray of that length. Examples: Input: N = 10, arr[] = {2, 3, 5, 3, 2, 3, 1, 3, 2, 7}Output: -1-1 3 2 2 2 1 1 1 1Explanation:For length = 1, no element is common in ev
    15+ min read
  • Minimum increment by k operations to make all equal
    You are given an array of n-elements, you have to find the number of operations needed to make all elements of array equal. Where a single operation can increment an element by k. If it is not possible to make all elements equal print -1. Example : Input : arr[] = {4, 7, 19, 16}, k = 3Output : 10Inp
    6 min read
  • Minimum increment operations to make K elements equal
    Given an array arr[] of N elements and an integer K, the task is to make any K elements of the array equal by performing only increment operations i.e. in one operation, any element can be incremented by 1. Find the minimum number of operations required to make any K elements equal.Examples: Input:
    11 min read
  • Minimum operation to make all elements equal in array
    Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
    11 min read
  • Minimum increment or decrement operations required to make the array sorted
    Given an array arr[] of N integers, the task is to sort the array in non-decreasing order by performing the minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples: Input: arr
    15+ min read
  • Minimum operations required to make two elements equal in Array
    Given array A[] of size N and integer X, the task is to find the minimum number of operations to make any two elements equal in the array. In one operation choose any element A[i] and replace it with A[i] & X. where & is bitwise AND. If such operations do not exist print -1. Examples: Input:
    9 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Minimum delete operations to make all elements of array same
    Given an array of n elements such that elements may repeat. We can delete any number of elements from the array. The task is to find a minimum number of elements to be deleted from the array to make it equal.Examples: Input: arr[] = {4, 3, 4, 4, 2, 4} Output: 2 After deleting 2 and 3 from array, arr
    10 min read
  • Minimum no. of operations required to make all Array Elements Zero
    Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences