974. Subarray Sums Divisible by K

Tapan RachchhTapan Rachchh
1 min read
class Solution:
    def subarraysDivByK(self, nums: List[int], k: int) -> int:
        prefixSum = 0
        ans = 0
        reminders = {}
        reminders[0] = [1]

        for i, num in enumerate(nums):
            prefixSum += num
            m = prefixSum % k

            if m in reminders:
                ans += len(reminders[m])                
                reminders[m].append(i)
            else:
                reminders[m] = [i]

        return ans
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh