Length of smallest subarray to be removed to make sum of remaining elements divisible by K | Function to find the length of the smallest subarray to be removed such that sum of elements is divisible by K ; Stores the remainder of each arr [ i ] when divided by K ; Stores total sum of elements ; K has been added to each arr [ i ] to handle - ve integers ; Update the total sum ; Remainder when total_sum is divided by K ; If given array is already divisible by K ; Stores curr_remainder and the most recent index at which curr_remainder has occurred ; Stores required answer ; Add current element to curr_sum and take mod ; Update current remainder index ; If mod already exists in map the subarray exists ; If not possible ; Print the result ; Given array arr [ ] ; Size of array ; Given K ; Function Call
function removeSmallestSubarray ( arr , n , k ) { let mod_arr = new Array ( n ) ; let total_sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { mod_arr [ i ] = ( arr [ i ] + k ) % k ; total_sum += arr [ i ] ; } let target_remainder = total_sum % k ; if ( target_remainder == 0 ) { document . write ( " " ) ; return ; } let map1 = new Map ( ) ; map1 . set ( 0 , - 1 ) ; let curr_remainder = 0 ; let res = Number . MAX_SAFE_INTEGER ; for ( let i = 0 ; i < n ; i ++ ) { curr_remainder = ( curr_remainder + arr [ i ] + k ) % k ; map1 . set ( curr_remainder , i ) ; let mod = ( curr_remainder - target_remainder + k ) % k ; if ( map1 . has ( mod ) ) res = Math . min ( res , i - map1 . get ( mod ) ) ; } if ( res == Number . MAX_SAFE_INTEGER res == n ) { res = - 1 ; } document . write ( res ) ; } let arr = [ 3 , 1 , 4 , 2 ] ; let N = arr . length ; let K = 6 ; removeSmallestSubarray ( arr , N , K ) ;