← Home

560. Subarray Sum Equals K

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
prefix sumsC++Markdown
560

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 560. Subarray Sum Equals K, the solution in this repository is mainly a prefix sums solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: prefix sums.

The notes already sitting in the source point us in the right direction:

  • time: O(n^2), space: O(n)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are subarraySum.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 904 ms, faster than 5.05% of C++ online submissions for Subarray Sum Equals K.
02//Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Subarray Sum Equals K.
03//time: O(n^2), space: O(n)
04class Solution {
05public:
06    int subarraySum(vector<int>& nums, int k) {
07        int ans = 0;
08        int n = nums.size();
09        
10        //convert "nums" to prefix sum
11        for(int i = 1; i < n; i++){
12            nums[i] += nums[i-1];
13        }
14        
15        for(int low = 0; low < n; low++){
16            for(int high = low; high < n; high++){
17                int cursum = nums[high] - ((low > 0) ? nums[low-1] : 0);
18                if(cursum == k) ans++;
19            }
20        }
21        
22        return ans;
23    }
24};
25
26//Approach #3 : calculate cumulative sum for every start point
27//Runtime: 476 ms, faster than 24.49% of C++ online submissions for Subarray Sum Equals K.
28//Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Subarray Sum Equals K.
29//time: O(n^2), space: O(1)
30class Solution {
31public:
32    int subarraySum(vector<int>& nums, int k) {
33        int ans = 0, n = nums.size();
34        for(int start = 0; start < n; start++){
35            int sum = 0;
36            for(int end = start; end < n; end++){
37                sum += nums[end];
38                if(sum == k) ans++;
39            }
40        }
41        return ans;
42    }
43};
44
45//Approach #4 Using hashmap
46//Runtime: 44 ms, faster than 54.94% of C++ online submissions for Subarray Sum Equals K.
47//Memory Usage: 13.8 MB, less than 70.67% of C++ online submissions for Subarray Sum Equals K.
48//time: O(N), space: O(N)
49class Solution {
50public:
51    int subarraySum(vector<int>& nums, int k) {
52        int ans = 0, sum = 0;
53        
54        //count the occurrence of cumulative sum
55        map<int, int> counter;
56        
57        counter[0] = 1;
58        
59        for(int i = 0; i < nums.size(); i++){
60            sum += nums[i];
61            //"sum"(current cumulative sum) - last cumulative sum(counter[?]) = k
62            //we can substract last cumulative sum from current cumulative sum to get k, and there are counter[sum - k] possibilities
63            if(counter.find(sum - k) != counter.end()){
64                ans += counter[sum - k];
65            }
66            //occurrence of prefix sum
67            counter[sum]++;
68        }
69        
70        return ans;
71    }
72};

Cost

Complexity

Time
O(N), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.