Modify given array by incrementing first occurrence of every element by K | 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
function printSequence ( A , n , k ) { var mp = new Map ( ) ; var sol = [ ] ; A . forEach ( x => { sol . push ( x ) ; } ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( ! mp . has ( sol [ i ] ) || mp . get ( sol [ i ] ) . size == 0 ) { var tmp = new Set ( ) ; tmp . add ( i ) mp . set ( sol [ i ] , tmp ) } else { var idxx = [ ... mp . get ( sol [ i ] ) ] . sort ( ( a , b ) => a - b ) [ 0 ] ; var idx = idxx ; var x = mp . get ( sol [ i ] ) ; x . delete ( idxx ) ; mp . set ( sol [ i ] , x ) ; sol [ idx ] += k ; if ( ! mp . has ( sol [ idx ] ) ) mp . set ( sol [ idx ] , new Set ( ) ) x = mp . get ( sol [ idx ] ) ; x . add ( idx ) ; mp . set ( sol [ idx ] , x ) ; x = mp . get ( sol [ i ] ) ; x . add ( i ) ; mp . set ( sol [ i ] , x ) ; } } sol . forEach ( x => { document . write ( x + " " ) ; } ) ; } var N = 5 ; var K = 6 ; var A = [ 1 , 4 , 1 , 1 , 4 ] ; printSequence ( A , N , K ) ;