---
# System prepended metadata

title: '#15 Zero Sum Subarray'
tags: [Medium, Array]

---

# #15 Zero Sum Subarray

###### tags:`Array` `Medium`

## Zero Sum Subarray 

You're given a list of integers `nums`. Write a function that returns a boolean representing whether there exists a zero-sum subarray of `nums`.
A zero-sum subarray is any subarray where all of the values add up to zero. A subarray is any contiguous section of the array. For the purposes of this problem, a subarray can be as small as one element and as long as the original array.

## Sample Input
```js
nums = [-5, -5, 2, 3, -2]
```

## Sample Output
```js
True // The subarray [-5, 2, 3] has a sum of 0
```

<br>

:::spoiler **Optimal Space & Time Complexity**
```
O(n) time | O(n) space - where n is the length of nums
```
:::

<br>

<hr/>

## Solutions

### Official Solution 1
```javascript=
// O(n) time | O(n) space - where n is the length of nums
function zeroSumSubarray(nums) {
  const sums = new Set([0]);
  let currentSum = 0;
  for (const num of nums) {
    currentSum += num;
    if (sums.has(currentSum)) return true;
    sums.add(currentSum);
  }
  return false;
}
```
<br>

---

### Everyone's

Everyone's content is basically the same.

:::spoiler Hao
```javascript=
/**
 * Time complexity is O(n) which n is nums.length
 * Space complexity is O(n) which n is nums.length
 */

function zeroSumSubarray(nums) {
  let runningSum = 0;
  const sums = new Set([runningSum]);

  for (let num of nums) {
    runningSum += num;
    if (sums.has(runningSum)) return true;

    sums.add(runningSum);
  }

  return false;
}
```

:::

<br>



:::spoiler 月
```javascript=
/* Time: O(n) -> Iteration
   Space: O(n) -> new set
   n is the length of nums. 
*/
function zeroSumSubarray(nums) {
  let sum = 0;
  const set = new Set();
  for(const num of nums){
    sum += num;
    if (set.has(sum) || sum === 0) {
      return true;
    }
    set.add(sum); 
  }
  return false;
}
```
:::

<br>

:::spoiler YC
```javascript=
function zeroSumSubarray(nums) {
  const sumSet = new Set([0]);
  let currSum = 0;
  for(let i = 0; i < nums.length; i++){
    currSum += nums[i];
    if(sumSet.has(currSum)) {
      return true;
    }
    sumSet.add(currSum)
  }
  return false
}
```
:::

<br>


#### backlog

:::spoiler 東
```javascript=

```
:::

<br>

---

## Supplement / Discussion

- A + 0 = A