BackmediumHashing Adobe

Subarray Divisible by K Solution

Problem Statement

Given an array of integers and a batch size K, count the number of contiguous subarrays whose total output is divisible by K.

Example 1
Input
[4,5,0,-2,-3,1]
Output
8

Explanation: Step-by-step explanation for the input [4,5,0,-2,-3,1]: 1. Calculate the prefix sum array: [4, 9, 9, 7, 4, 4] 2. Count the occurrences of each prefix sum that is divisible by K (K = 3 in this case). 3. The prefix sum 0 occurs 8 times, so the output is 8.

Example 2
Input
[0,0,0,1,1,1,1,0,0,0,1,1,1,1]
Output
6

Explanation: Step-by-step explanation for the input [0,0,0,1,1,1,1,0,0,0,1,1,1,1]: 1. Calculate the prefix sum array: [0, 0, 0, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 8] 2. Count the occurrences of each prefix sum that is divisible by K (K = 3 in this case). 3. The prefix sum 0 occurs 6 times, so the output is 6.

Constraints

  • 1 <= n <= 3 * 10^4
  • 2 <= k <= 10^4
  • -10^4 <= arr[i] <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free