Given an array of integers, return any non-empty subarray whose elements sum up to zero.
{
"arr": [5, 1, 2, -3, 7, -4]
}
Output:
[1, 3]
Sum of [1, 2, -3]
subarray is zero. It starts at index 1 and ends at index 3 of the given array, so [1, 3]
is a correct answer. [3, 5]
is another correct answer.
{
"arr": [1, 2, 3, 5, -9]
}
Output:
[-1]
There is no non-empty subarray with sum zero.
[start_index, end_index]
of a non-empty zero sum subarray; zero-based indices; both start_index
and end_index
are included in the subarray.[-1]
.Constraints:
We provided two solutions.
We will refer to the length of the input array as n
.
A naive approach would be to iterate over all possible subarrays of input array arr
, such that while on subarray[i, j]
, i.e. subarray starting from i
-th index and ending at j
-th index, find sum of elements in it and if it's zero, return [i, j]
. If no such subarray is found, return [-1]
.
O(n2).
As we are iterating over all possible subarrays of input array arr
, time complexity will be O(n2).
O(1).
We are not storing anything extra.
O(n).
Space used for input: O(n).
Auxiliary space used: O(1).
Space used for output: O(1).
So, total space complexity: O(n) + O(1) + O(1) = O(n).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n^2).
* Auxiliary space: O(1).
* Total space: O(n).
*/
static ArrayList<Integer> sum_zero(ArrayList<Integer> arr) {
// To store current sum
long sum = 0;
// We are trying to find sum of each subarray[i, n - 1] where 0 <= i <= (n - 1).
for (int i = 0; i < arr.size(); i++) {
sum = 0;
// To calculate sum of subarray starting from i and ending at n-1
for (int j = i; j < arr.size(); j++) {
sum += arr.get(j);
// If sum == 0 means we found our subarray having sum as 0 with start index i
// and end index j
if (sum == 0) {
return new ArrayList<Integer>(Arrays.asList(i, j));
}
}
}
// If no subarray as sum equal to zero found then we will return [-1]
return new ArrayList<Integer>(Arrays.asList(-1));
}
Notice that if there exists a zero sum subarray[i, j]
in a given input array arr
, then prefix sum (denote it as prefix where prefix[k] = arr[0] + arr[1] + arr[2] + ... + arr[k]
) prefix[j]
should be equal to prefix[i - 1]
, as prefix[j] = prefix[i - 1] + (arr[i] + arr[i + 1] + ... + arr[j])
, where the term in bracket is sum of subarray[i, j]
, which is 0.
Considering this fact, build prefix sum array prefix
. If for some i
, j
, 0 <= i <= j < n
, prefix[i - 1] = prefix[j]
, then subarray[i, j]
is the zero sum subarray.
O(n).
To find out if any two sums of subarrays are equal or not we will store them in HashMap
as prefix[k]
(i.e. sum) as key and k
as value. To maintain a hashmap it will take O(n) time complexity in the worst case to get and store n
sums.
O(n).
We are using hashmap to store sums. It will take O(n) of space.
O(n).
Space used for input: O(n).
Auxiliary space used: O(n).
Space used for output: O(1).
So, total space complexity: O(n) + O(n) + O(1) = O(n).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
static ArrayList<Integer> sum_zero(ArrayList<Integer> arr) {
// To store prefix sum i.e. sum of subarray starting at index 0 and ending at index i
// Key of hashmap will be sum and value will be index i for prefix sum
HashMap<Long, Integer> map = new HashMap<>();
// To check whether prefix sum it self is equal to zero
map.put(0l, -1);
// To store current sum
long sum = 0;
for (int i = 0; i < arr.size(); i++) {
// To check if we encountered with value which itself is zero
if(arr.get(i) == 0){
return new ArrayList<Integer>(Arrays.asList(i, i));
}
// Adding current value in current sum
sum += arr.get(i);
// If we found value sum in our hashmap means we have encountered with this sum before
// means arr[0, map.get(sum)] = sum and
// arr[0, map.get(sum)] + arr[map.get(sum) + 1, i] = sum
// which implies arr[map.get(sum) + 1, i] = 0 and hence interval we are looking for is
// start = map.get(sum) + 1 and end = i
if (map.containsKey(sum)) {
return new ArrayList<Integer>(Arrays.asList(map.get(sum) + 1, i));
} else {
map.put(sum, i);
}
}
// If no subarray having sum = 0 found then we will return [-1]
return new ArrayList<Integer>(Arrays.asList(-1));
}
We hope that these solutions to zero sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Given an array of integers, return any non-empty subarray whose elements sum up to zero.
{
"arr": [5, 1, 2, -3, 7, -4]
}
Output:
[1, 3]
Sum of [1, 2, -3]
subarray is zero. It starts at index 1 and ends at index 3 of the given array, so [1, 3]
is a correct answer. [3, 5]
is another correct answer.
{
"arr": [1, 2, 3, 5, -9]
}
Output:
[-1]
There is no non-empty subarray with sum zero.
[start_index, end_index]
of a non-empty zero sum subarray; zero-based indices; both start_index
and end_index
are included in the subarray.[-1]
.Constraints:
We provided two solutions.
We will refer to the length of the input array as n
.
A naive approach would be to iterate over all possible subarrays of input array arr
, such that while on subarray[i, j]
, i.e. subarray starting from i
-th index and ending at j
-th index, find sum of elements in it and if it's zero, return [i, j]
. If no such subarray is found, return [-1]
.
O(n2).
As we are iterating over all possible subarrays of input array arr
, time complexity will be O(n2).
O(1).
We are not storing anything extra.
O(n).
Space used for input: O(n).
Auxiliary space used: O(1).
Space used for output: O(1).
So, total space complexity: O(n) + O(1) + O(1) = O(n).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n^2).
* Auxiliary space: O(1).
* Total space: O(n).
*/
static ArrayList<Integer> sum_zero(ArrayList<Integer> arr) {
// To store current sum
long sum = 0;
// We are trying to find sum of each subarray[i, n - 1] where 0 <= i <= (n - 1).
for (int i = 0; i < arr.size(); i++) {
sum = 0;
// To calculate sum of subarray starting from i and ending at n-1
for (int j = i; j < arr.size(); j++) {
sum += arr.get(j);
// If sum == 0 means we found our subarray having sum as 0 with start index i
// and end index j
if (sum == 0) {
return new ArrayList<Integer>(Arrays.asList(i, j));
}
}
}
// If no subarray as sum equal to zero found then we will return [-1]
return new ArrayList<Integer>(Arrays.asList(-1));
}
Notice that if there exists a zero sum subarray[i, j]
in a given input array arr
, then prefix sum (denote it as prefix where prefix[k] = arr[0] + arr[1] + arr[2] + ... + arr[k]
) prefix[j]
should be equal to prefix[i - 1]
, as prefix[j] = prefix[i - 1] + (arr[i] + arr[i + 1] + ... + arr[j])
, where the term in bracket is sum of subarray[i, j]
, which is 0.
Considering this fact, build prefix sum array prefix
. If for some i
, j
, 0 <= i <= j < n
, prefix[i - 1] = prefix[j]
, then subarray[i, j]
is the zero sum subarray.
O(n).
To find out if any two sums of subarrays are equal or not we will store them in HashMap
as prefix[k]
(i.e. sum) as key and k
as value. To maintain a hashmap it will take O(n) time complexity in the worst case to get and store n
sums.
O(n).
We are using hashmap to store sums. It will take O(n) of space.
O(n).
Space used for input: O(n).
Auxiliary space used: O(n).
Space used for output: O(1).
So, total space complexity: O(n) + O(n) + O(1) = O(n).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
static ArrayList<Integer> sum_zero(ArrayList<Integer> arr) {
// To store prefix sum i.e. sum of subarray starting at index 0 and ending at index i
// Key of hashmap will be sum and value will be index i for prefix sum
HashMap<Long, Integer> map = new HashMap<>();
// To check whether prefix sum it self is equal to zero
map.put(0l, -1);
// To store current sum
long sum = 0;
for (int i = 0; i < arr.size(); i++) {
// To check if we encountered with value which itself is zero
if(arr.get(i) == 0){
return new ArrayList<Integer>(Arrays.asList(i, i));
}
// Adding current value in current sum
sum += arr.get(i);
// If we found value sum in our hashmap means we have encountered with this sum before
// means arr[0, map.get(sum)] = sum and
// arr[0, map.get(sum)] + arr[map.get(sum) + 1, i] = sum
// which implies arr[map.get(sum) + 1, i] = 0 and hence interval we are looking for is
// start = map.get(sum) + 1 and end = i
if (map.containsKey(sum)) {
return new ArrayList<Integer>(Arrays.asList(map.get(sum) + 1, i));
} else {
map.put(sum, i);
}
}
// If no subarray having sum = 0 found then we will return [-1]
return new ArrayList<Integer>(Arrays.asList(-1));
}
We hope that these solutions to zero sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Attend our free webinar to amp up your career and get the salary you deserve.