Given an array A of N integers and an integer K, write a program to print the number of subarrays in A whose sum is divisible by K.
Question
Given an array A of N integers and an integer K, write a program to print the number of subarrays in A whose sum is divisible by K.
Solution
Sure, here is a step-by-step approach to solve the problem:
-
Initialize a variable
count
to 0, which will keep track of the number of subarrays whose sum is divisible by K. -
Create a dictionary
remainder_count
to store the count of remainders obtained when the cumulative sum of elements in the array is divided by K. Initializeremainder_count
with a single key-value pair: (0, 1), as the cumulative sum of an empty subarray is 0. -
Initialize a variable
cumulative_sum
to 0, which will store the cumulative sum of elements in the array. -
Iterate through each element
num
in the array A. -
Update the
cumulative_sum
by addingnum
to it. -
Calculate the remainder
remainder
whencumulative_sum
is divided by K. -
If
remainder
is negative, add K to it to make it positive. This is done to handle negative remainders. -
If
remainder
exists inremainder_count
, incrementcount
by the value associated withremainder
inremainder_count
. -
If
remainder
does not exist inremainder_count
, add it toremainder_count
with a value of 1. -
Increment the value associated with
remainder
inremainder_count
by 1. -
After iterating through all the elements in the array, print the value of
count
, which represents the number of subarrays whose sum is divisible by K.
Here is a sample implementation in Python:
def count_subarrays(A, K):
count = 0
remainder_count = {0: 1}
cumulative_sum = 0
for num in A:
cumulative_sum += num
remainder = cumulative_sum % K
if remainder < 0:
remainder += K
if remainder in remainder_count:
count += remainder_count[remainder]
remainder_count[remainder] = remainder_count.get(remainder, 0) + 1
return count
# Example usage
A = [4, 5, 0, -2, -3, 1]
K = 5
result = count_subarrays(A, K)
print(result) # Output: 7
This implementation has a time complexity of O(N), where N is the length of the array A.
Similar Questions
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Given a list of integers, count and return the number of times each value appears as an array of integers.
Initialize an array/list with five integers. Write a program to find the sumand average of these n
Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to .
how many windows would exist in an array with N elements and window size K a)N+K+1B)N-K-1C)N-K+1D)N+K-1
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.