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.
It is worse than you think.
There are potentially Θ(n²) uninterrupted subsequences that add up to zero, as in the following example:
0 0 0 0 0 0 0 0 0
(Here, every subsequence adds up to zero.)
Therefore, any algorithm that prints out the start and end index of all the required subsequences will necessarily have o(n²) worst-case complexity. Printing out their elements will require Θ(n³) time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.