![]() |
VOOZH | about |
Given an array arr[] containing both positive and negative integers, check whether there exists a non-empty subarray whose sum is equal to zero.
Examples:
Input: arr[] = [4, 2, -3, 1, 6]
Output: true
Explanation: There is a subarray with zero sum from index 1 to 3 .Sum of subarray [2,-3,1] is 0 .
Input: arr[]=[4, 2, 0, 1, 6]
Output: true
Explanation: The third element is zero. A single element is also a sub-array.Input: arr[]=[-3, 2, 3, 1, 6]
Output: false
Table of Content
Generate every subarray using two nested loops and calculate the sum of each subarray. Check if subarray sum is 0 then return true. Otherwise, if no such subarray found then return false.
false
The idea is to iterate through the array and for every element arr[i], calculate the sum of elements from 0 to i (this can simply be done as sum += arr[i]). If the current sum has been seen before, then there must be a zero-sum subarray. Hashing is used to store the sum values so that sum can be stored quickly and find out whether the current sum is seen before or not.
arr[] = {1, 4, -2, -2, 5, -4, 3}
Consider all prefix sums, one can notice that there is a subarray with 0 sum when :
- Either a prefix sum repeats
- Or, prefix sum becomes 0.
Prefix sums for above array are: 1, 5, 3, 1, 6, 2, 5
Since prefix sum 1 repeats, we have a subarray with 0 sum.Corner Case : The whole prefix can also be 0, so along with repetition of prefix sum, we also need to check if prefix sum becomes 0.
false