Replace duplicates with greater than previous duplicate value

25 May, 2021
Given an array of elements and change the array in such a way that all the elements on the array are distinct. If you are replacing a value, then the replacing value should be greater than the previous value and, after modification, the sum of the elements should be as small as possible.
Examples: 
Input : arr = {1, 2, 2, 5, 8, 8, 8} Output : 1 2 3 5 8 9 10 8 is replaced with 9 (A non-existing element greater than 8). Next, duplicate occurrence of 8 is replaced with 10.
Input : arr = {1, 2, 5, 7, 8, 8, 7} Output : 1 2 5 7 8 9 10
Input : arr = {9, 9, 9, 9, 9} Output : 9 10 11 12 13 
Source: Paytm Interview Experience 30.
This problem is a variation of this article. In the above article, we had to replace the duplicates with the greatest value so far. But in this problem, we have to replace elements with duplicates greater than the previous duplicate value. The idea is to find the next greater element to be replaced to minimize the total sum. To find the next greater element, we have to iterate from the repeated element till the INT_MAX until the next greater element is found.
Below is the implementation of the above approach.  
C++
Java
Python3
C#
Javascript
// CPP program to replace every repeating// element with next greater element.#include <bits/stdc++.h>using namespace std; void replaceElements(int arr[], int n){    unordered_set<int> s;     for (int i = 0; i < n; i++) {         // check whether the element is        // repeated or not        if (s.find(arr[i]) == s.end())            s.insert(arr[i]);         else {             // find the next greatest element            for (int j = arr[i] + 1; j < INT_MAX; j++) {                if (s.find(j) == s.end()) {                    arr[i] = j;                    s.insert(j);                    break;                }            }        }    }} int main(){    int arr[] = { 1, 2, 5, 7, 8, 8, 7 };    int n = sizeof(arr) / sizeof(arr[0]);     replaceElements(arr, n);     for (int i = 0; i < n; i++)        cout << arr[i] << " ";    cout << "\n";}
// Java program to replace every repeating// element with next greater element.import java.util.HashSet;import java.util.Set; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate {     private static void replaceElements(int[] arr, int n)    {        Set<Integer> st = new HashSet<>();        for (int i = 0; i < n; i++) {            // check whether the element is            // repeated or not            if (!st.contains(arr[i])) {                st.add(arr[i]);            }            else {                // find the next greatest element                for (int j = arr[i] + 1; j < Integer.MAX_VALUE; j++) {                    if (!st.contains(j)) {                        arr[i] = j;                        st.add(j);                        break;                    }                }            }        }    }    public static void main(String[] args)    {        int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 };        int n = arr.length;        replaceElements(arr, n);         for (int i = 0; i < n; i++) {            System.out.print(arr[i] + " ");        }    }}
# Python3 program to replace every repeating# element with next greater element.import sys def replaceElements(arr, n):     s = []     for i in range (n):         # check whether the element        # is repeated or not        if arr[i] not in s:            s.append(arr[i])         else :             # find the next greatest element            for j in range(arr[i] + 1, sys.maxsize) :                if j not in s:                    arr[i] = j                    s.append(j)                    break # Driver Codeif __name__ == "__main__":     arr = [ 1, 2, 5, 7, 8, 8, 7 ]    n = len(arr)     replaceElements(arr, n)     for i in range(n):        print (arr[i], end = " ")    print () # This code is contributed# by ChitraNayal
// C# program to replace every repeating// element with next greater element.using System;using System.Collections.Generic; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate{    private static void replaceElements(int[] arr, int n)    {        HashSet<int> st = new HashSet<int>();        for (int i = 0; i < n; i++)        {            // check whether the element is            // repeated or not            if (!st.Contains(arr[i]))            {                st.Add(arr[i]);            }            else            {                // find the next greatest element                for (int j = arr[i] + 1; j < int.MaxValue; j++)                {                    if (!st.Contains(j))                    {                        arr[i] = j;                        st.Add(j);                        break;                    }                }            }        }    }         // Driver Code    public static void Main(String[] args)    {        int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 };        int n = arr.Length;        replaceElements(arr, n);         for (int i = 0; i < n; i++)        {            Console.Write(arr[i] + " ");        }    }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to replace every repeating// element with next greater element.         function replaceElements(arr,n)    {        let st = new Set();        for (let i = 0; i < n; i++) {            // check whether the element is            // repeated or not            if (!st.has(arr[i])) {                st.add(arr[i]);            }            else {                // find the next greatest element                for (let j = arr[i] + 1; j < Number.MAX_VALUE; j++) {                    if (!st.has(j)) {                        arr[i] = j;                        st.add(j);                        break;                    }                }            }        }    }         let arr=[1, 2, 5, 7, 8, 8, 7];    let n = arr.length;    replaceElements(arr, n);       for (let i = 0; i < n; i++) {        document.write(arr[i] + " ");    }              // This code is contributed by avanitrachhadiya2155</script>
1 2 5 7 8 9 10
 
ukasp
indolia143
princiraj1992
avanitrachhadiya2155
cpp-unordered_set
Paytm
Technical Scripter 2018
Arrays
Hash
Paytm
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence