C++ program to Replace Duplicates with Greater than Previous Duplicate Value

C++ProgrammingServer Side Programming

A series of integers is given in this article. Let's say we have an array of four elements without counting the repetitive elements, [2, 2, 5, 5, 7, 8, 7], and we have to make the array distinctive. Changing a value with one that is greater than the previous one is possible.

In the above array, element 2 at index 1 becomes 3 as the next greater element. 5 at index 3 becomes 6 as the next greater and so on. So, in the end, our array becomes [2 3 5 6 7 8 9] and should minimize the sum of elements during the process.

Let us look at some input scenarios −

Assume the input string given has a duplicate for every element, the resultant obtained would be −

Input: [1, 1, 2, 2, 4, 4, 6, 6]
Result: [1 2 3 4 5 6 7 8]

Assume the input string given has multiple duplicates for only one element, the resultant obtained would be −

Input: [1, 1, 1, 1, 1, 1]
Result: [1 2 3 4 5 6]

A sequence is obtained since the new value must be greater than the previous duplicate value.

Example (Using Vector ADT)

Following is a C++ program that replaces duplicate elements in an array with greater values than the previous duplicate values −

#include <iostream> #include <vector> #include <set> using namespace std; void solve(vector<int>& arr) { set<int> s; for(int &val : arr) { if(s.find(val) != s.end()) { for(int j=val+1;j<INT32_MAX;j++) { if(s.find(j) == s.end()) { val = j; break; } } } s.insert(val); } } void print(vector<int>& arr) { for(int val : arr) cout << val << " "; cout << "
"
; } int main() { vector<int> arr = { 5,2,5,7,8,8,7 }; print(arr); solve(arr); print(arr); return 0; }

Output

5 2 5 7 8 8 7
5 2 6 7 8 9 10

Example (Without Using Vector ADT)

Following is a C++ program that replaces duplicate elements in an array with greater values than the previous duplicate values without using the vector abstract data type −

#include <bits/stdc++.h>
using namespace std;

int main()
{
   int array[] = { 1, 7, 2, 3, 4, 4, 5, 6, 6 };
   int n = sizeof(array) / sizeof(array[0]);
   for (int i = 0; i < n; i++)
      cout << array[i] << " ";
   cout << "
"; unordered_set<int> set; for (int i = 0; i < n; i++) { // check whether the element in a set is repeated or not if (set.find(array[i]) == set.end()) set.insert(array[i]); else { for (int j = array[i] + 1; j < INT_MAX; j++) { // finding the next maximum element if (set.find(j) == set.end()) { array[i] = j; set.insert(j); break; } } } } for (int i = 0; i < n; i++) cout << array[i] << " "; cout << "
"; }

Output

1 7 2 3 4 4 5 6 6 
1 7 2 3 4 5 6 8 9 

Conclusion

Using 1 for loop to iterate over the array, we save the elements in the set. Then using another for loop, we find the next maximum we can replace this with. We use the set as a hash map here. We can also use unordered_map or map here.

raja
Updated on 10-Aug-2022 12:54:28

Advertisements