Pages

07/06/2021

[Java] Find integer subarray which sums up to zero

I was watching this video regarding the following problem: given an integer array, find a subarray that sums up to 0.

In my opinion the whole array is a valid subarray, however, a single element isn't, since the problem states we need to perform a sum operation which requires at least two elements.

I decided to implement against that requirement, which slightly modifies the approach.

The overall idea is the same, we walk the array and keep summing up elements and track which sums we have seen so far. If there exists a portion of the array that sums up to 0, its contribution to the overall sum will be 0 and therefore we will find a duplicate result within our sums set. We could also simply have a sequence that sums to 0 directly, eg [-1,1] which is also a valid result.

In this variant, if we encounter a zero, we simply skip it but if we have two consecutive zeros, then we can return the [0,0] subarray which is valid as it includes at least two operands.

Additionally, we do not track the indices for each encountered sum, instead, as soon as we find a duplicate result or the current sum is 0, we stop walking the array and go backwards decrementing our current sum until we subtract enough from it to match our target (the duplicate result we're looking for).

All indices between where we stopped and where we arrived now are our subarray of sum 0. This subarray will be the smallest possible subarray to sum up to 0, therefore won't contain leading or trailing zeros, eg: [0, -1, 1] input will return [-1, 1] result.

This algorithm runs in O(N) time and O(N) space since we need an additional set to store the seen sums.

You can check my implementation of findSubarrayOfSumZero on my Gist along with some tests in FindSubarrayOfSumZeroJTests.

No comments:

Post a Comment

With great power comes great responsibility