Subarray Sum Equals K
- Difficulty: Medium
- Source: LeetCode 560 – Subarray Sum Equals K
Problem credit: This note is for practicing the LeetCode problem “Subarray Sum Equals K”. For the full official statement, examples, and judge, see the LeetCode problem page.
Description
You are given an integer array nums and an integer k, and the task is to return the number of non-empty contiguous subarrays whose elements add up to k.
A subarray is defined as a sequence of one or more elements that appear consecutively in the original array, without reordering or skipping indices.
Example
Example 1:
- Input:
nums = [1, 1, 1],k = 2 - Output:
2 - Explanation: The subarrays
[1, 1]using indices[0, 1]and[1, 2]both sum to 2, so the answer is 2.
Example 2:
- Input:
nums = [1, 2, 3],k = 3 - Output:
2 - Explanation: The subarrays
[1, 2]and[3]each sum to 3, giving a total count of 2.
You can experiment with inputs that include negative numbers, such as [2, 2, -4, 1, 1, 2] and various k values, to see how multiple overlapping subarrays can share the same sum.
Code
# LeetCode 560: Subarray Sum Equals K
# Credit: Problem from LeetCode (see problem page for full statement and tests).
def subarraySum(nums: List[int], k: int) -> int:
"""
Write your solution here.
Requirements:
- Count all non-empty contiguous subarrays whose sum is exactly k.
- nums may contain positive, negative, and zero values.
- Return the total number of such subarrays.
"""
# To be solved
raise NotImplementedError