LeetCode – 560 : Subarray Sum Equals K

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

Example 1:

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

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Idea – 1

Try all of the possible O(n^2) subarrays, time O(n^2) and space O(1).
[code lang="java"]
class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        int n = nums.length;
        
        for(int i = 0; i < n; ++i)
        {
            int sum = 0;
            for(int j = i; j < n; ++j)
            {
                sum += nums[j];
                if(sum==k)
                {
                    ++count;
                }
            }
        }
        
        return count;
    }
}
[code]

Runtime: 117 ms, faster than 28.52% of Java online submissions for Subarray Sum Equals K.Memory Usage: 38.2 MB, less than 95.55% of Java online submissions for Subarray Sum Equals K.

Idea – 2

If we needed to find two numbers that sum to K, we would be using a hash table. In a similar spirit, the problem could be thought of as finding two cumsums whose difference is k. Therefore if we have two indices p and q (p < q) and \sum_{i=0}^{i=q}\ -\ \sum_{i=0}^{i=p}\ =\ k, then we have a subarray between p and q that sums to K. We could do it in linear time and linear space, compared to first idea, this boils down to a space-time trade-off.
[code lang="java"]
class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        int n = nums.length;
        
        HashMap<Integer, Integer> map = new HashMap<>();
        
        // Cumsum(0..j) == K case
        map.put(0, 1);
        
        // cumulative sum
        int cumsum = 0;
        for(int x : nums)
        {
            cumsum += x;
            int delta = cumsum-k;
            
            count += map.getOrDefault(delta, 0);
            
            map.put( cumsum, map.getOrDefault(cumsum, 0)+1 );
        }
        
        
        return count;
    }
}
[code]

Runtime: 14 ms, faster than 85.19% of Java online submissions for Subarray Sum Equals K.Memory Usage: 36.8 MB, less than 98.65% of Java online submissions for Subarray Sum Equals K.