ntree.ai
ntree.aiSubarray Sum Equals K

Solutions

1. Brute Force

O(n²) time | O(1) space

Intuition

We can take every possible subarray, add up its elements and count every time it adds up to k.

Algorithm

  1. Create a count integer variable with initial value 0.
  2. Iterate through the outer loop from the first element to the last element with i index.
  3. For each outer loop iteration, create a total integer variable with initial value 0 and iterate through the inner loop from the element at i to the last element with j index.
    • Add the element at j to total.
    • Increase count by one when total is equal to k.
  4. Return count when both loops finish.
k = 7
3
4
7
2
−3
1
012345
ij
total = 3, count = 0
1 / 22

Code

Code
Python
def subarraySum(nums: list[int], k: int) -> int:
count = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
count += 1
return count
/**
* @param {number[]} nums
* @param {number} k
* @returns {number}
*/
var subarraySum = function (nums, k) {
let count = 0
for (let i = 0; i < nums.length; i++) {
let total = 0
for (let j = i; j < nums.length; j++) {
total += nums[j]
if (total === k) count++
}
}
return count
}
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int total = 0;
for (int j = i; j < nums.length; j++) {
total += nums[j];
if (total == k) count++;
}
}
return count;
}
}

2. Prefix Sums and Hash Table

O(n) time | O(n) space

Intuition

We can check each element one by one and count how many subarrays that end with that element add up to k in constant time.

That count is how many earlier prefix sums are equal to the prefix sum at this element minus k. To store how many prefix sums add up to each value, we will use a hash map.

Algorithm

  1. Create a hash map and put the value 1 for the key 0, which is the prefix sum before the first element.
  2. Create count and total integer variables with initial value 0.
  3. Iterate through the loop from the first element to the last element.
    • Add the element to total.
    • Increase count by the value in the hash map at key total - k.
    • Add a new pair to the hash map with key total and value 1 for the current prefix sum or increase the value by one if the key already exists.
  4. Return count.
k = 7
3
4
7
2
−3
1
012345
i
0→1
3 − 7 = −4, −4 is not in the hash map, count = 0
1 / 7

Code

Code
Python
def subarraySum(nums: list[int], k: int) -> int:
sums = {0: 1}
count = 0
total = 0
for n in nums:
total += n
count += sums.get(total - k, 0)
sums[total] = sums.get(total, 0) + 1
return count
/**
* @param {number[]} nums
* @param {number} k
* @returns {number}
*/
var subarraySum = function (nums, k) {
const sums = new Map([[0, 1]])
let count = 0
let total = 0
for (const n of nums) {
total += n
count += sums.get(total - k) ?? 0
sums.set(total, (sums.get(total) ?? 0) + 1)
}
return count
}
import java.util.HashMap;
import java.util.Map;
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> sums = new HashMap<>();
sums.put(0, 1);
int count = 0;
int total = 0;
for (int n : nums) {
total += n;
count += sums.getOrDefault(total - k, 0);
sums.merge(total, 1, Integer::sum);
}
return count;
}
}
Was the explanation clear?
def subarraySum(nums: list[int], k: int) -> int:
pass
 

Press Visualise to step through your code.