VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-subarrays-with-0-sum/

⇱ Print all subarrays with 0 sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all subarrays with 0 sum

Last Updated : 25 Jan, 2025

Given an array arr[] of size n, the task is to print all subarrays in the array which has sum 0.

Examples:

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

Input: arr = [1, 2, -3, 3, -1, -1]
Output:

Subarray found from Index 0 to 2
Subarray found from Index 2 to 3
Subarray found from Index 3 to 5

[Naive Approach] By generating all possible subarrays - O(n2) time and O(1) auxiliary space

The very basic approach is to considers all possible subarrays and checks if their sum is zero. Although this approach is simple but inefficient also for large arrays.


Output
Subarray found from Index 0 to 10
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

Time Complexity: O(N2) since we are using 2 loops.
Auxiliary Space: O(1), as constant extra space is required.

[Expected Approach] Using Hashing - O(n) time and O(n) auxiliary space

A more efficient approach is to use hashing to store the cumulative sum of elements and their indices. This allows for checking if a subarray with zero sum exists in constant time.

  1. Create a hash map to store the cumulative sum and corresponding indices.
  2. Initialize the cumulative sum to zero.
  3. Traverse the array:
    • Add the current element to the cumulative sum.
    • If the cumulative sum is zero, a subarray from the beginning to the current index is found.
    • If the cumulative sum is already present in the hash map, it means there is a subarray with zero sum.
    • Store the cumulative sum and index in the hash map.

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

Time Complexity: O(n), where n is the number of elements in the array.
Auxiliary Space: O(n), for storing the hash map.

Comment
Article Tags:
Article Tags: