BudiBadu Logo

Subarray Sum Equals K

Hash Table Medium 1 views
Like0

Given an integer array nums and an integer k, return the total number of continuous subarrays whose sum equals k.

The hash table trick is to track prefix sums and how often each sum has appeared. If current prefix is sum, then any previous prefix sum-k forms a valid subarray ending at the current index.

This turns a slow O(n^2) scan into O(n) using a map of prefix frequencies.

Example 1:

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

Example 2:

Input: nums = [1,2,3], k = 3
Output: 2

Example 3:

Input: nums = [1,-1,0], k = 0
Output: 3

Algorithm Flow

Recommendation Algorithm Flow for Subarray Sum Equals K - Budibadu
Recommendation Algorithm Flow for Subarray Sum Equals K - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int subarray_sum_equals_k(int[] nums, int k) {
        Map<Integer, Integer> count = new HashMap<>();
        count.put(0, 1);
        int s = 0, ans = 0;
        for (int x : nums) {
            s += x;
            ans += count.getOrDefault(s - k, 0);
            count.put(s, count.getOrDefault(s, 0) + 1);
        }
        return ans;
    }
}