AlgoMaster Logo

Subarray Sums Divisible by K

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The most straightforward way to solve the problem is to consider every possible subarray of the given array. For each subarray, compute its sum and check if it’s divisible by K. This approach is simple and works fine for small input sizes.

Steps:

  1. Initialize a counter to zero which will store the number of subarrays satisfying the condition.
  2. Iterate over all possible starting points of subarrays.
  3. For each starting point, iterate over all possible ending points.
  4. Calculate the sum of the current subarray.
  5. Check if this sum is divisible by K. If so, increment the counter.
  6. Return the counter after checking all subarrays.

Code:

2. Remainder + HashMap

Intuition:

The brute force approach works but is inefficient for larger arrays. We can optimize this by leveraging the properties of prefix sums and remainders. If the prefix sum up to i is sum[0..i] and prefix sum up to j is sum[0..j], and both sum[0..i] % K and sum[0..j] % K are equal, then the subarray sum[i+1..j] is divisible by K.

We can use a HashMap to keep track of all seen remainder counts, making it easier to find the potential starting points for subarrays that end at each position in the array.

Steps:

  1. Initialize a HashMap to store the count of each remainder.
  2. Keep a running sum of the elements.
  3. Calculate the remainder of the current sum by K.
  4. If this remainder has been seen before, it means there's a subarray ending at the current position with a sum divisible by K.
  5. Update the count of subarrays.
  6. Update the remainder's count in the HashMap.

Code: