Skip to main content

Command Palette

Search for a command to run...

count subarrays

Published
1 min readView as Markdown
import java.util.HashMap;

class Solution {
    public static long findSubarray(long[] arr, int n) {
        HashMap<Long, Integer> freq = new HashMap<>();
        long sum = 0;
        long count = 0;
        freq.put(0L, 1);

        for (int i = 0; i < n; i++) {
            sum += arr[i];
            if (freq.containsKey(sum)) {
                count += freq.get(sum);
            }
            if (freq.containsKey(sum)) {
                freq.put(sum, freq.get(sum) + 1);
            } else {
                freq.put(sum, 1);
            }

        }

        return count;
    }
}

More from this blog

Amit singh's blog

235 posts