Untitled

 avatar
unknown
plain_text
6 months ago
920 B
2
Indexable
public int subarraysDivByK(int[] nums, int k) {
        int count = 0;
        int prefixSum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        
        // Initialize map with 0 remainder having count 1
        map.put(0, 1);
        
        for (int num : nums) {
            prefixSum += num;
            
            // Compute remainder of prefixSum with k
            int remainder = prefixSum % k;
            
            // Handle negative remainders
            if (remainder < 0) {
                remainder += k;
            }
            
            // Check if this remainder has been seen before
            if (map.containsKey(remainder)) {
                count += map.get(remainder);
            }
            
            // Update the map with the current remainder
            map.put(remainder, map.getOrDefault(remainder, 0) + 1);
        }
        
        return count;
    }
Editor is loading...
Leave a Comment