560. Subarray Sum Equals K

https://leetcode.com/problems/subarray-sum-equals-k/

Problem

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

Constraints:

  • The length of the array is in range [1, 20,000].

  • The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Solution

1. O(N2)O(N^2) using prefix sum

class Solution {
public:
    int subarraySum(vector<int>& nums, const int k) {
        int prefix[nums.size() + 1];
        prefix[0] = 0;
        int count = 0;
        for (int i = 1; i <= nums.size(); ++i) prefix[i] = prefix[i - 1] + nums[i - 1];
        for (int i = 1; i <= nums.size(); ++i) {
            for (int j = i; j <= nums.size(); ++j) {
                if (prefix[j] - prefix[i - 1] == k) ++count;
            }
        }
        return count;
    }
};

2. O(N)O(N) using hash map

  • #hash

  • #veryimportant

  • #prefix

Last updated

Was this helpful?