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
- Create a
countinteger variable with initial value0. - Iterate through the outer loop from the first element to the last element with
iindex. - For each outer loop iteration, create a
totalinteger variable with initial value0and iterate through the inner loop from the element atito the last element withjindex.- Add the element at
jtototal. - Increase
countby one whentotalis equal tok.
- Add the element at
- Return
countwhen both loops finish.
k = 7
3
4
7
2
−3
1
012345
ij
total = 3, count = 0
1 / 22
k = 7
3
4
7
2
−3
1
012345
i
j
Code
Code
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
- Create a hash map and put the value
1for the key0, which is the prefix sum before the first element. - Create
countandtotalinteger variables with initial value0. - Iterate through the loop from the first element to the last element.
- Add the element to
total. - Increase
countby the value in the hash map at keytotal - k. - Add a new pair to the hash map with key
totaland value1for the current prefix sum or increase the value by one if the key already exists.
- Add the element to
- 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
k = 7
3
4
7
2
−3
1
012345
i
0→1
3→1
7→1
14→1
16→1
13→1
Code
Code
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.