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

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

Similar Reads

Using Nested loop (Brute force Approach)

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

Using map object in JavaScript

This approach uses more optimized `Map` data structure to store cumulative sums and their corresponding indices. It efficiently finds the length of the longest subarray with a zero sum within the given array by updating the maximum length based on the difference between current and previously encountered sum indices....

Dynamic Programming Approach

This code employs dynamic programming principles to efficiently find the length of the longest subarray with a zero sum within the given array. By dynamically updating the maximum length based on the difference between current and previously encountered sum indices, it ensures optimal performance in determining the longest subarray with a zero sum....