Given an array of positive and negative numbers. Find if there is a subarray (of size at least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Using Prefix Sum
Logic
Maintain a prefix sum
If at any point the element of the prefix sum is 0
Then obviously we found that the sum form beginning till that element is 0
If at any point the prefix sum repeats itself
We know that the sum of the element after the first occurrence to the last occurrence makes a sum of 0. This is the reason that the prefix sum was able to repeat itself.