Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Math
Amazon
Google
Subarray Sums Divisible By K

Count the number of contiguous subarrays whose sum is divisible by a given integer k.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums and an integer k, count how many contiguous subarrays have a sum that is divisible by k.

A subarray is a non-empty, contiguous segment of the array. A sum is divisible by k when its remainder after division by k is 0.

Your task is to return the total number of such subarrays.

Key idea to think about

A direct check of every subarray is too slow for large arrays, so you should look for a way to reuse information about cumulative sums and their remainders.

Input Format

  • nums: an integer array
  • k: a positive integer

Output Format

  • Return a single integer: the number of contiguous subarrays whose sum is divisible by k.

Constraints

  • 1 <= nums.length
  • k > 0
  • nums may contain positive, negative, and zero values
  • Use 64-bit counting if needed to avoid overflow in intermediate totals
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [4,5,0,-2,-3,1], k = 5

Output

7

Explanation

The valid subarrays are counted by comparing prefix-sum remainders. In total, there are 7 contiguous subarrays with sum divisible by 5.

Example 2

Input

nums = [5], k = 9

Output

0

Explanation

The only subarray has sum 5, which is not divisible by 9.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.