Register for our webinar

### How to Nail your next Technical Interview

1 hour
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
Step 1
Step 2
Congratulations!
You have registered for our webinar
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

## You may be missing out on a 66.5% salary hike*

### Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Help us know you better!

## How many years of coding experience do you have?

Oops! Something went wrong while submitting the form.

## FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Oops! Something went wrong while submitting the form.

# Sum Zero Problem Statement

Given an array of integers, return any non-empty subarray whose elements sum up to zero.

## Example One

``````{
"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.

## Example Two

``````{
"arr": [1, 2, 3, 5, -9]
}
``````

Output:

``````[-1]
``````

There is no non-empty subarray with sum zero.

## Notes

• The output is an array of type `[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.
• If there are multiple such subarrays, you can return any.
• If no zero sum subarray is found, return `[-1]`.

Constraints:

• 1 <= length of the input array <= 5 * 105
• -109 <= number in the array <= 109

We provided two solutions.

We will refer to the length of the input array as `n`.

# Sum Zero Solution 1: Brute Force

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]`.

## Time Complexity

O(n2).

As we are iterating over all possible subarrays of input array `arr`, time complexity will be O(n2).

## Auxiliary Space Used

O(1).

We are not storing anything extra.

## Space Complexity

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).

## Code For Sum Zero Solution 1: Brute Force

``````    /*
* 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));
}
``````

# Sum Zero Solution 2: Optimal

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.

## Time Complexity

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.

## Auxiliary Space Used

O(n).

We are using hashmap to store sums. It will take O(n) of space.

## Space Complexity

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).

## Code For Sum Zero Solution 2: Optimal

``````    /*
* 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:

### Try yourself in the Editor

Note: Input and Output will already be taken care of.

# Sum Zero Problem Statement

Given an array of integers, return any non-empty subarray whose elements sum up to zero.

## Example One

``````{
"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.

## Example Two

``````{
"arr": [1, 2, 3, 5, -9]
}
``````

Output:

``````[-1]
``````

There is no non-empty subarray with sum zero.

## Notes

• The output is an array of type `[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.
• If there are multiple such subarrays, you can return any.
• If no zero sum subarray is found, return `[-1]`.

Constraints:

• 1 <= length of the input array <= 5 * 105
• -109 <= number in the array <= 109

We provided two solutions.

We will refer to the length of the input array as `n`.

# Sum Zero Solution 1: Brute Force

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]`.

## Time Complexity

O(n2).

As we are iterating over all possible subarrays of input array `arr`, time complexity will be O(n2).

## Auxiliary Space Used

O(1).

We are not storing anything extra.

## Space Complexity

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).

## Code For Sum Zero Solution 1: Brute Force

``````    /*
* 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));
}
``````

# Sum Zero Solution 2: Optimal

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.

## Time Complexity

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.

## Auxiliary Space Used

O(n).

We are using hashmap to store sums. It will take O(n) of space.

## Space Complexity

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).

## Code For Sum Zero Solution 2: Optimal

``````    /*
* 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: