Check if a subarray of size K exists whose elements form a number divisible by 3 | Function to find the K size subarray ; Check if the first K elements forms a number which is divisible by 3 ; Using Sliding window technique ; Calculate sum of next K size subarray ; Check if sum is divisible by 3 ; Update the indices of the subarray ; If no such subarray is found ; Print the subarray ; Given array and K ; Function Call
function findSubArray ( arr , k ) { var ans = [ ] ; var i , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } var found = 0 ; if ( sum % 3 == 0 ) { ans = [ 0 , i - 1 ] ; found = 1 ; } for ( var j = i ; j < arr . length ; j ++ ) { if ( found == 1 ) break ; sum = sum + arr [ j ] - arr [ j - k ] ; if ( sum % 3 == 0 ) { ans = [ j - k + 1 , j ] ; found = 1 ; } } if ( found == 0 ) ans = [ - 1 , 0 ] ; if ( ans . first == - 1 ) { cout << - 1 ; } else { for ( i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } } var arr = [ 84 , 23 , 45 , 12 , 56 , 82 ] ; var K = 3 ; findSubArray ( arr , K ) ;