
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum Increment to Make Array Unique in C++
Suppose we have an array of integers A, here a move consists of choosing any A[i], and incrementing it by 1. We have to find the least number of moves to make every value in A unique. So if the input is like [3,2,1,2,1,7], then the output will be 6, as after 6 moves, the array could be [3,4,1,2,5,7], it can be shown with 5 or less moves that it is impossible for the array to have all distinct values.
To solve this, we will follow these steps −
ret:= 0
sort array A
create one set called visited to keep track which value is considered before
for i in range 1 to size of array A – 1
if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1
return ret.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int minIncrementForUnique(vector<int>& A) { int ret = 0; sort(A.begin(), A.end()); set <int> visited; for(int i = 1; i < A.size(); i++){ if(A[i] <= A[i - 1]){ ret+= (A[i - 1] + 1) - A[i]; A[i] = A[i - 1] + 1; } } return ret; } }; main(){ vector<int> v1 = {3,2,1,2,1,7}; Solution ob; cout << (ob.minIncrementForUnique(v1)); }
Input
[3,2,1,2,1,7]
Output
6
- Related Articles
- Program to count minimum deletions needed to make character frequencies unique in Python
- Minimum removals to make array sum even in C++
- Minimum removals to make array sum odd in C++
- Minimum removals from array to make max – min
- Minimum insertions to make a Co-prime array in C++
- Minimum removals from array to make GCD Greater in Python
- Minimum operations to make XOR of array zero in C++
- Minimum removals from array to make GCD Greater in C++
- Finding minimum steps to make array elements equal in JavaScript
- Program to find minimum moves to make array complementary in Python
- Minimum operation to make all elements equal in array in C++
- Find minimum operations needed to make an Array beautiful in C++
- Auto increment in MongoDB to store sequence of Unique User ID?
- Program to find minimum operations to make array equal using Python
- Minimum delete operations to make all elements of array same in C++.

Advertisements