📖
Coding interview questions
  • 👋Coding Interview
  • Easy
    • Two number sum
    • Validate Subsequence
    • Sorted Squared Array
    • Tournament Winner
    • Non-Constructible Change
    • Find Closest Value in BTS
    • Branch sum
    • Node Depths
    • Depth-first Search
    • Minimum Waiting Time
    • Class Photos
  • Medium
    • Three Number Sum
    • Smallest Difference
    • Move Element To End
    • Monotonic Array
    • Spiral Traverse
    • Longest Peak
    • Array Of Products
    • First Duplicate Value
    • Merge Overlapping Intervals
    • Zero Sum Subarray
    • BST Traversal
    • Validate BST
    • Min Height BST
    • Find Kth Largest Value In BST
    • Reconstruct BST
    • Invert Binary Tree
  • Hard
    • Three Number Sum
  • Really-Hard
    • Three Number Sum
Powered by GitBook
On this page
  1. Medium

Zero Sum Subarray

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

nums = [-5, -5, 2, 3, -2]

Sample Output

True // The subarray [-5, 2, 3] has a sum of 0
// 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;
}

// Do not edit the line below.
exports.zeroSumSubarray = zeroSumSubarray;

PreviousMerge Overlapping IntervalsNextBST Traversal

Last updated 2 years ago

Page cover image