Efficiently merging two sorted arrays with O ( 1 ) extra space |  ; Find maximum element of both array ; Increment by one to avoid collision of 0 and maximum element of array in modulo operation ; Recover back original element to compare ; Update element by adding multiplication with new number ; Update element by adding multiplication with new number ; Process those elements which are left in array a ; Process those elements which are left in array b ; Finally update elements by dividing with maximum element ; Finally update elements by dividing with maximum element ; Driver Code ; Length of a ; Length of b ; Function Call
function mergeArray ( a , b , n , m ) { let mx = 0 ; for ( let i = 0 ; i < n ; i ++ ) { mx = Math . max ( mx , a [ i ] ) ; } for ( let i = 0 ; i < m ; i ++ ) { mx = Math . max ( mx , b [ i ] ) ; } mx ++ ; let i = 0 , j = 0 , k = 0 ; while ( i < n && j < m && k < ( n + m ) ) { let e1 = a [ i ] % mx ; let e2 = b [ j ] % mx ; if ( e1 <= e2 ) { if ( k < n ) a [ k ] += ( e1 * mx ) ; else b [ k - n ] += ( e1 * mx ) ; i ++ ; k ++ ; } else { if ( k < n ) a [ k ] += ( e2 * mx ) ; else b [ k - n ] += ( e2 * mx ) ; j ++ ; k ++ ; } } while ( i < n ) { let el = a [ i ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; i ++ ; k ++ ; } while ( j < m ) { let el = b [ j ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; j ++ ; k ++ ; } for ( let i = 0 ; i < n ; i ++ ) a [ i ] = parseInt ( a [ i ] / mx ) ; for ( let i = 0 ; i < m ; i ++ ) b [ i ] = parseInt ( b [ i ] / mx ) ; return ; } var a = [ 3 , 5 , 6 , 8 , 12 ] ; var b = [ 1 , 4 , 9 , 13 ] ; var n = a . length ; var m = b . length ; mergeArray ( a , b , n , m ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( a [ i ] + " " ) ; document . write ( ' ' ) document . write ( " " ) ; for ( let i = 0 ; i < m ; i ++ ) document . write ( b [ i ] + " " ) ;