Say that we have an array of N integers and want to find all subsequences of consecutive elements which have the sum of the equal to zero.
Example:
N = 9
array = [1, -2, 4, 5, -7, -4, 8, 3, -7]
Should output:
1 4
4 7
5 8
1 8
as each of the above are the start and end index of the subsequences with sum equal to zero.
I came to the conclusion that there are N * (N + 1) / 2
such possible subsequences which would conclude in O(N^2) complexity if using a naive algorithm that exhaustively searches over all the possible solutions.
I would like to know if there is any way to achieve this in O(N) complexity or something less than O(N^2)?
I am aware of the Subset sum problem which is a NP-complete problem but mine seems to be a bit easier as it only requires subsequences of consecutive elements.
Thank you in advance.