LeetCode – Subarray Sum Equals K (Java)

Given an array of integers and an integer k, find the total number of continuous subarrays whose sum equals to k.

Example 1:

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

Note that empty array is not considered as a subarray.

Java Solution

The sum problems can often be solved by using a hash map efficiently.

public int subarraySum(int[] nums, int k) {
    HashMap<Integer, Integer> map = new HashMap<>();
    map.put(0, 1);
    int count = 0;
    int sum = 0;
    //e.g., 1 1 2 1 1
    for(int i=0; i<nums.length; i++){
        sum += nums[i];
        int n = map.getOrDefault(sum-k, 0);
        count += n;
        map.put(sum, map.getOrDefault(sum,0)+1);
    return count;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";