Subarray Sum Equals K
Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
Function Signature:
from typing import List
def subarray_sum(nums: List[int], k: int) -> int:
"""
Count the number of continuous subarrays in 'nums' whose sum equals 'k'.
Parameters:
- nums: A list of integers.
- k: Target sum.
Returns:
- int: Total number of continuous subarrays whose sum equals 'k'.
"""
# Your code here
Example:
result = subarray_sum([1, 1, 1], 2)
print(result)
assert result == 2
# Explanation: The subarrays whose sum equals k=2 are [1, 1] and [1, 1].
result = subarray_sum([1, 2, 3], 3)
print(result)
assert result == 2
# Explanation: The subarrays whose sum equals k=3 are [1, 2] and [3].
result = subarray_sum([3, 4, 7, 2, -3, 1, 4, 2], 7)
print(result)
assert result == 4
# Explanation: The subarrays whose sum equals k=7 are [7], [3, 4], [7, 2, -3, 1], and [1, 4, 2].
result = subarray_sum([], 0)
print(result)
assert result == 0
# Explanation: Because the array is empty, there is no subarray whose sum equals k=0
result = subarray_sum([0], 0)
print(result)
assert result == 1
# Explanation: There is only one subarray, [0], whose sum equals k=0
result = subarray_sum([0], 1)
print(result)
assert result == 1
# Explanation: There is no subarray whose sum equals k=1
result = subarray_sum([0, 2, 3, 4], 1)
print(result)
assert result == 0
# Explanation: There is no subarray whose sum equals k=1
Note:
- The array can contain both positive and negative integers.
Instructions:
- Implement the
subarray_sum
function to solve the problem. - Use Python for your implementation.
- Ensure that your code includes clear comments to explain the logic.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊