Given an array, print all subarrays in the array which has sum 0.
Input: arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7] Output: Subarray found from Index 2 to 4 Subarray found from Index 2 to 6 Subarray found from Index 5 to 6 Subarray found from Index 6 to 9 Subarray found from Index 0 to 10
Related posts: Find if there is a subarray with 0 sum
A simple solution is to consider all subarrays one by one and check if sum of every subarray is equal to 0 or not. The complexity of this solution would be O(n^2).
A better approach is to use Hashing.
Do following for each element in the array
- Maintain sum of elements encountered so far in a variable (say sum).
- If current sum is 0, we found a subarray starting from index 0 and ending at index current index
- Check if current sum exists in the hash table or not.
- If current sum exists in the hash table, that means we have subarray(s) present with 0 sum that ends at current index.
- Insert current sum into the hash table
Below is C++ implementation of above idea –
Subarray found from Index 2 to 4 Subarray found from Index 2 to 6 Subarray found from Index 5 to 6 Subarray found from Index 6 to 9 Subarray found from Index 0 to 10
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find the character in first string that is present at minimum index in second string
- Top 20 Hashing Technique based Interview Questions
- Check if two arrays are equal or not
- Sum of all Subarrays | Set 1
- Find Surpasser Count of each element in array
- Palindrome Substring Queries
- Find frequency of each element in a limited range array in less than O(n) time
- Find subarray with given sum | Set 2 (Handles Negative Numbers)
- Find smallest range containing elements from k lists
- Implementing our Own Hash Table with Separate Chaining in Java
- Find the length of largest subarray with 0 sum
- Longest Consecutive Subsequence
- Find if there is a subarray with 0 sum
- Largest subarray with equal number of 0s and 1s
- Find subarray with given sum | Set 1 (Nonnegative Numbers)