Length of smallest subarray to be removed to make sum of remaining elements divisible by K | Java program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Size of array ; Given K ; Function Call
import java . util . * ; class GFG { static void removeSmallestSubarray ( int arr [ ] , int n , int k ) { int [ ] mod_arr = new int [ n ] ; int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mod_arr [ i ] = ( arr [ i ] + k ) % k ; total_sum += arr [ i ] ; } int target_remainder = total_sum % k ; if ( target_remainder == 0 ) { System . out . print ( "0" ) ; return ; } HashMap < Integer , Integer > map1 = new HashMap < > ( ) ; map1 . put ( 0 , - 1 ) ; int curr_remainder = 0 ; int res = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { curr_remainder = ( curr_remainder + arr [ i ] + k ) % k ; map1 . put ( curr_remainder , i ) ; int mod = ( curr_remainder - target_remainder + k ) % k ; if ( map1 . containsKey ( mod ) ) res = Math . min ( res , i - map1 . get ( mod ) ) ; } if ( res == Integer . MAX_VALUE res == n ) { res = - 1 ; } System . out . print ( res ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 4 , 2 } ; int N = arr . length ; int K = 6 ; removeSmallestSubarray ( arr , N , K ) ; } }