Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/d7f97c78faf141a4744e1d3ba0dc3206 to your computer and use it in GitHub Desktop.
Save yitonghe00/d7f97c78faf141a4744e1d3ba0dc3206 to your computer and use it in GitHub Desktop.
560. Subarray Sum Equals K (https://leetcode.com/problems/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.
// Array + Brutal force solution
// Time: O(n ^ 2), 212ms
// Space: O(1), 40.6mb
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
for(int i = 0; i < nums.length; i++) {
int sum = 0;
for(int j = 0; i + j < nums.length; j++) {
sum += nums[i + j];
if(sum == k) ans++;
}
}
return ans;
}
}
// Array + Hash table solution: store the <prefix sum, count> in a table; idea like 1 two sum
// Time: O(n), 11ms
// Space: O(n), 42.3mb
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
// Init the <sum, count> table
Map<Integer, Integer> table = new HashMap<>();
table.put(0, 1);
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
// Look up the table for prefix with a sum of sum - k: sum(i,j) = sum(0,j) - sum(0,i)
if(table.containsKey(sum - k)) ans += table.get(sum - k);
table.put(sum, table.getOrDefault(sum, 0) + 1);
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment