How to use 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.

Example: To demonstrate finding the longest subarray with zero sum using map method in JavaScript.

Javascript
function answer(arr) {
    let maxLength = 0;
    let sumIndexMap = new Map();
    let sum = 0;

    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];

        if (sum === 0) {
            maxLength = i + 1;
        } else if (sumIndexMap.has(sum)) {
            maxLength = Math
                .max(maxLength, i - sumIndexMap.get(sum));
        } else {
            sumIndexMap.set(sum, i);
        }
    }

    return maxLength;
}

let arr = [3, 2, -5, 3, -3, -4];
console.log(answer(arr));

Output
5

Time Complexity : O(n) , traversing the array

Space Complexity : O(n), using map object to store frequency

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