Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result . ; Initialize curr_sum as value of first element and starting point as 0 ; Add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver program
def subArraySum ( arr , n , sum_ ) : NEW_LINE INDENT curr_sum = arr [ 0 ] NEW_LINE start = 0 NEW_LINE i = 1 NEW_LINE while i <= n : NEW_LINE INDENT while curr_sum > sum_ and start < i - 1 : NEW_LINE INDENT curr_sum = curr_sum - arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT if curr_sum == sum_ : NEW_LINE INDENT print ( " Sum ▁ found ▁ between ▁ indexes " ) NEW_LINE print ( " % ▁ d ▁ and ▁ % ▁ d " % ( start , i - 1 ) ) NEW_LINE return 1 NEW_LINE DEDENT if i < n : NEW_LINE INDENT curr_sum = curr_sum + arr [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( " No ▁ subarray ▁ found " ) NEW_LINE return 0 NEW_LINE DEDENT arr = [ 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE sum_ = 23 NEW_LINE subArraySum ( arr , n , sum_ ) NEW_LINE