Open In App

JavaScript Program to Find Largest Subarray with a Sum Divisible by k

Last Updated : 26 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Finding the largest subarray with a sum divisible by a given integer ‘k’ is a common problem in JavaScript and other programming languages. This task involves identifying a contiguous subarray within an array of integers such that the sum of its elements is divisible by ‘k’ and is as long as possible. This problem is essential in various scenarios, including optimizing algorithms and data processing.

Examples:

Input: arr[] = {7,1,3,2,9} , k = 3
Output: 4
Explanation: The subarray is {1, 3, 2, 9} with sum 15, which is divisible by 3.

Input: arr[] = { 4, 5}, k = 2
Output: 1

Approach 1: Brute Force Approach

The brute force approach involves generating all possible subarrays and calculating their sums. For each sum, check if it’s divisible by ‘k’ and keep track of the largest subarray found so far.

Example:

Javascript




function largestSubarraySumDivisibleByK(arr, k) {
    let maxLength = 0;
  
    for (let start = 0;
        start < arr.length; start++) {
        let currentSum = 0;
  
        for (let end = start;
            end < arr.length; end++) {
            currentSum += arr[end];
  
            if (currentSum % k === 0 &&
                (end - start + 1) > maxLength) {
                maxLength = end - start + 1;
            }
        }
    }
  
    return maxLength;
}
  
const arr = [7, 1, 3, 2, 9];
const k = 3;
console.log(largestSubarraySumDivisibleByK(arr, k));


Output

4

Approach 2: Using Prefix Sum

We can use prefix sums to efficiently calculate subarray sums. By storing the cumulative sum of elements up to each position, you can quickly determine the sum of any subarray. To find the largest subarray divisible by ‘k’, you track the prefix sums modulo ‘k’ and store the indices where each remainder is first encountered.

Javascript




function largestSubarraySumDivisibleByK(arr, k) {
    const prefixSums = [0];
    let currentSum = 0;
    let maxLength = 0;
  
    for (let num of arr) {
        currentSum = (currentSum + num) % k;
        prefixSums.push(currentSum);
    }
  
    const remainderIndices = {};
  
    for (let i = 0; i < prefixSums.length; i++) {
        if (remainderIndices
            .hasOwnProperty(prefixSums[i])) {
            maxLength = Math.max(maxLength,
                i - remainderIndices[prefixSums[i]]);
        } else {
            remainderIndices[prefixSums[i]] = i;
        }
    }
  
    return maxLength;
}
  
const arr = [7, 1, 3, 2, 9];
const k = 3;
console.log(largestSubarraySumDivisibleByK(arr, k));


Output

4

Approach 3: Using a Hash Map

An efficient approach involves using a hash map to store the prefix sums modulo ‘k’ and their corresponding indices.

Javascript




function largestSubarraySumDivisibleByK(arr, k) {
    let currentSum = 0;
    let maxLength = 0;
    const remainderIndices = { 0: -1 };
  
    for (let i = 0; i < arr.length; i++) {
        currentSum += arr[i];
        const remainder = (currentSum % k + k) % k;
  
        if (remainderIndices
            .hasOwnProperty(remainder)) {
            maxLength = Math.max(maxLength,
                i - remainderIndices[remainder]);
        } else {
            remainderIndices[remainder] = i;
        }
    }
  
    return maxLength;
}
  
const arr = [7, 1, 3, 2, 9];
const k = 3;
console.log(largestSubarraySumDivisibleByK(arr, k));


Output

4


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads