Modify given array by incrementing first occurrence of every element by K | C ++ Program to implement the above approach ; Print the required final sequence ; Stores the array element - index pairs ; Stores the required sequence ; Insert all array elements ; If current element has not occurred previously ; Otherwise ; Iterator to the first index containing sol [ i ] ; Remove that occurrence ; Increment by K ; Insert the incremented element at that index ; Print the final sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSequence ( vector < int > & A , int n , int k ) { unordered_map < int , set < int > > mp ; vector < int > sol ; for ( int x : A ) sol . push_back ( x ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . find ( sol [ i ] ) == mp . end ( ) || mp [ sol [ i ] ] . size ( ) == 0 ) { mp [ sol [ i ] ] . insert ( i ) ; } else { auto idxx = mp [ sol [ i ] ] . begin ( ) ; int idx = * idxx ; mp [ sol [ i ] ] . erase ( idxx ) ; sol [ idx ] += k ; mp [ sol [ idx ] ] . insert ( idx ) ; mp [ sol [ i ] ] . insert ( i ) ; } } for ( int x : sol ) { cout << x << " ▁ " ; } } int main ( ) { int N = 5 ; int K = 6 ; vector < int > A = { 1 , 4 , 1 , 1 , 4 } ; printSequence ( A , N , K ) ; }