

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check for Subarray in the original array with 0 sum JavaScript
We are required to write a JavaScript function that takes in an array of Numbers with some positive and negative values. We are required to determine whether there exists a subarray in the original array whose net sum is 0 or not.
Our function should return a boolean on this basis.
Approach
The approach here is simple. We iterate over the array using a for loop, calculate the cumulative sum up to that particular element. And if any point the cumulative becomes 0 or attains a value it has previously attained, then there exists a subarray with sum 0. Otherwise there exists no subarray with sum 0.
Therefore, let's write the code for this function −
Example
const arr = [4, 2, -1, 5, -2, -1, -2, -1, 4, -1, 5, -2, 3]; const zeroSum = arr => { const map = new Map(); let sum = 0; for(let i = 0; i < arr.length; i++){ sum += arr[i]; if(sum === 0 || map.get(sum)){ return true; }; map.set(sum, i); }; return false; }; console.log(zeroSum(arr));
Output
The output in the console will be −
true
- Related Questions & Answers
- Contiguous subarray with 0 and 1 in JavaScript
- Find if there is a subarray with 0 sum in C++
- Maximum subarray sum in circular array using JavaScript
- C++ code to check query for 0 sum
- Return the sum of two consecutive elements from the original array in JavaScript
- Subarray sum with at least two elements in JavaScript
- Find Sum of all unique subarray sum for a given array in C++
- Removing smallest subarray to make array sum divisible in JavaScript
- Left right subarray sum product - JavaScript
- Maximum contiguous sum of subarray in JavaScript
- Subarray with the greatest product in JavaScript
- Check if subarray with given product exists in an array in Python
- C/C++ Program for Largest Sum Contiguous Subarray?
- Maximize the subarray sum after multiplying all elements of any subarray with X in C++
- Add two consecutive elements from the original array and display the result in a new array with JavaScript
Advertisements