Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Function to print subarray with sum as given sum ; create an empty map ; if curr_sum is equal to target sum we found a subarray starting from index 0 and ending at index i ; If curr_sum - sum already exists in map we have found a subarray with target sum ; if value is not present then add to hashmap ; If we reach here , then no subarray exists ; Driver program to test above function
def subArraySum ( arr , n , Sum ) : NEW_LINE INDENT Map = { } NEW_LINE curr_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_sum = curr_sum + arr [ i ] NEW_LINE if curr_sum == Sum : NEW_LINE INDENT print ( " Sum ▁ found ▁ between ▁ indexes ▁ 0 ▁ to " , i ) NEW_LINE return NEW_LINE DEDENT if ( curr_sum - Sum ) in Map : NEW_LINE INDENT print ( " Sum ▁ found ▁ between ▁ indexes " ,   \ Map [ curr_sum - Sum ] + 1 , " to " , i ) NEW_LINE return NEW_LINE DEDENT Map [ curr_sum ] = i NEW_LINE DEDENT print ( " No ▁ subarray ▁ with ▁ given ▁ sum ▁ exists " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE Sum = - 10 NEW_LINE subArraySum ( arr , n , Sum ) NEW_LINE DEDENT