Count Subarrays with Sum Divisible by K
Updated
Problem statement
Given an integer array arr and a positive integer k, return the number of non-empty contiguous subarrays whose element sum is divisible by k.
A subarray is a contiguous sequence of elements from arr. A sum s is divisible by k when s % k = 0.
Function
countDivisibleSubarrays(arr: int[], k: int) → longExamples
Example 1
arr = [2,3,1]k = 2return = 3The qualifying subarrays are [2], [3,1], and [2,3,1], with sums 2, 4, and 6.
Example 2
arr = [1,2,3,4]k = 1return = 10Every integer sum is divisible by 1, so all 4 × 5 / 2 = 10 non-empty subarrays qualify.
Example 3
arr = [-1,2,9]k = 2return = 2The qualifying subarrays are [2], whose sum is 2, and [-1,2,9], whose sum is 10.
Constraints
1 <= arr.length <= 1041 <= k <= 104-109 <= arr[i] <= 109- The answer fits in a signed 64-bit integer.
More Visa Online Assessment questions
- Count Prime Values in SubtreesOA · Seen Nov 2026
- Lock CodeOA · Seen Nov 2026
- Minimum-Sum Tree Fill with Unit StepsOA · Seen Nov 2026
- Longest Non-Decreasing Substring After Pair SwapsOA · Seen Oct 2026
- Count Attack Vectors by Divisor RangeOA · Seen Oct 2026
- Minimum Operations to Reduce a Transaction LedgerOA · Seen Oct 2026
- Count Valid Space-Delimited WordsOA · Seen Oct 2026
- Earliest Common Meeting StartOA · Seen Oct 2026
- Maximum Index-Weighted Sum with Disjoint SwapsOA · Seen Oct 2026
- Maximum Equalized Substrings After One Adjacent SwapOA · Seen Sep 2026
Similar questions at other companies
- Count Subarrays with a Perfect-Square ProductMicrosoft · OAMicrosoft interview questions
- Count Zero-Sum FragmentsTesla · OATesla interview questions
- Count Stable Server SubsegmentsScale AI · OAScale AI interview questions
- Number of Unique Elements After Modifications 🍁Infosys · OAInfosys interview questions
- Count Paired Subarrays Reaching a TargetZipRecruiter · OAZipRecruiter interview questions
- Count Subarrays with Sum KIndeed · OAIndeed interview questions
- Count Subarrays With Given XORInMobi · OAInMobi interview questions
- Beautiful SubarraysAtlassian · OAAtlassian interview questions
- Find Security LevelAmazon · OA
- Subarray Sum Equals KServiceNow · ONSITE INTERVIEWServiceNow interview questions