Removing smallest subarray to make array sum divisible in JavaScript

We are required to write a JavaScript function that takes in an array of positive integers as the first argument and a positive integer as the second argument.

The function should figure out and return the length of the smallest subarray that we should delete from the original array in order to make its sum divisible by the number specified by the second argument.

For example, if we have an array [3, 8, 2, 6] and want the sum divisible by 9, we need to remove the subarray [8, 2] of length 2.

Problem Analysis

The approach uses modular arithmetic and prefix sums. We calculate the total sum modulo the target number to find what remainder needs to be removed. Then we use a hash map to track prefix sum positions and find the shortest subarray with the required remainder.

Example Input

const arr = [3, 8, 2, 6];
const num = 9;

Expected output: 2 (remove subarray [8, 2])

Solution Implementation

const arr = [3, 8, 2, 6];
const num = 9;

const minimumDeletion = (arr = [], num) => {
    const diff = arr.reduce((a, b) => a + b) % num;
    let res = diff == 0 ? 0 : arr.length;
    
    for (let i = 0, sum = 0, map = {0: -1}; i < arr.length; i++) {
        sum += arr[i];
        const target = (sum % num - diff + num) % num;
        
        if (map[target] != undefined) {
            res = Math.min(res, i - map[target]);
        }
        
        map[sum % num] = i;
    }
    
    return res == arr.length ? -1 : res;
};

console.log(minimumDeletion(arr, num));
2

How It Works

The algorithm follows these steps:

  1. Calculate remainder: Find diff = totalSum % num - this is what we need to remove
  2. Use prefix sums: Track cumulative sums and their positions in a hash map
  3. Find target: For each position, calculate what prefix sum we need to find the shortest subarray
  4. Update result: Keep track of the minimum subarray length found

Step-by-Step Walkthrough

const arr = [3, 8, 2, 6];
const num = 9;

// Total sum = 19, diff = 19 % 9 = 1 (need to remove remainder 1)
const totalSum = arr.reduce((a, b) => a + b);
console.log("Total sum:", totalSum);
console.log("Remainder to remove:", totalSum % num);

// Prefix sums: [3, 11, 13, 19]
// Modulo 9: [3, 2, 4, 1]
let prefixSum = 0;
for (let i = 0; i < arr.length; i++) {
    prefixSum += arr[i];
    console.log(`Position ${i}: element=${arr[i]}, prefixSum=${prefixSum}, mod=${prefixSum % num}`);
}
Total sum: 19
Remainder to remove: 1
Position 0: element=3, prefixSum=3, mod=3
Position 1: element=8, prefixSum=11, mod=2
Position 2: element=2, prefixSum=13, mod=4
Position 3: element=6, prefixSum=19, mod=1

Alternative Test Case

// Test with array already divisible
const arr2 = [6, 3, 9];
const num2 = 9;

console.log("Array:", arr2);
console.log("Sum:", arr2.reduce((a, b) => a + b));
console.log("Minimum deletion needed:", minimumDeletion(arr2, num2));
Array: [ 6, 3, 9 ]
Sum: 18
Minimum deletion needed: 0

Conclusion

This algorithm efficiently finds the shortest subarray to remove using modular arithmetic and prefix sums in O(n) time complexity. It returns -1 if the entire array needs to be removed, making it a robust solution for the subarray deletion problem.

Updated on: 2026-03-15T23:19:00+05:30

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements