How to use Nested loop (Brute force Approach) In Javascript
This code employs a brute-force technique, iterating through all possible subarrays to find the longest subarray with a zero-sum within the given array. It utilizes nested loops to calculate the sum of each subarray and updates the maximum length accordingly.
Example: To demonstrate finding the length of the longest subarray with a zero-sum within the given array, using iteration in Javascript
function subArray(arr) {
let maxLen = 0;
for (let i = 0; i < arr.length; i++) {
let current_Sum = 0;
for (let j = i; j < arr.length; j++) {
current_Sum += arr[j];
if (current_Sum === 0) {
maxLen = Math.max(maxLen, j - i + 1);
}
}
}
return maxLen;
}
const arr = [3, 2, -5, 3, -3, -4];
console.log("Length of longest subarray with zero sum:",
subArray(arr));
Output
Length of longest subarray with zero sum: 5
Time Complexity : O(n2) , using nested loop.
Space Complexity : O(1) , using constant space.
Length of the Longest Subarray with Zero Sum using JavaScript
JavaScript allows us to find the longest subarray with zero-sum. We have to return the length of the longest subarray whose sum is equal to zero.
There are several approaches in JavaScript to achieve this which are as follows:
Table of Content
- Using Nested loop (Brute force Approach)
- Using map object in JavaScript
- Dynamic Programming Approach