Problem 265961 · medium · Level 02 Linear Data Structures

Segments Divisible by k

hash maps · prefix sums · modular arithmetic

Given nums and a positive integer k, count the contiguous non-empty subarrays whose sum is divisible by k.

Examples

Input:  nums = [3, 1, -5, 2, 6], k = 3
Output: 4
Explanation: [3], [-5,2], [-5,2,6] and [6].

Input:  nums = [5], k = 5
Output: 1

Constraints

  • 0 <= len(nums) <= 10**5, 1 <= k <= 10**4
  • -10**4 <= nums[i] <= 10**4
  • Target complexity: O(n) time.

Goals

  • Count subarrays via prefix remainders
  • Normalise negative remainders
Starting Python…