Smallest Subarray with Sum K from an Array | Function to find the length of the smallest subarray with sum K ; Stores the frequency of prefix sums in the array ; Initialize len as INT_MAX ; If sum of array till i - th index is less than K ; No possible subarray exists till i - th index ; Find the exceeded value ; If exceeded value is zero ; Driver Code
function subArraylen ( arr , n , K ) { var mp = new Map ( ) ; mp . set ( arr [ 0 ] , 0 ) ; for ( var i = 1 ; i < n ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; mp . set ( arr [ i ] , i ) ; } var len = 10000000000 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < K ) continue ; else { var x = arr [ i ] - K ; if ( x == 0 ) len = Math . min ( len , i ) ; if ( ! mp . has ( x ) ) continue ; else { len = Math . min ( len , i - mp . get ( x ) ) ; } } } return len ; } var arr = [ 1 , 2 , 4 , 3 , 2 , 4 , 1 ] ; var n = arr . length ; var K = 7 ; var len = subArraylen ( arr , n , K ) ; if ( len == 1000000000 ) { document . write ( " " ) ; } else { document . write ( len ) ; }