Subarray Sum Equals K
Given an integer array nums and an integer k, return the total number of subarrays whose sum is equal to k.
A subarray is a contiguous part of the array containing at least one element.
Example 1
Input
nums = [1, 1, 1] k = 2
Output
2
Explanation
The subarrays whose sum is 2 are:
[1, 1]
[1, 1]
Therefore, the answer is 2.
Example 2
Input
nums = [1, 2, 3] k = 3
Output
2
Explanation
The valid subarrays are:
[1, 2]
[3]
Both have sum 3.
Constraints
Hints:
Hint 1
Use a running prefix sum while traversing the array.
Hint 2
If the current prefix sum is sum, a previous prefix sum of:
sum - k
means the subarray between those two positions has sum k.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 26, 2026
Last updated
Aug 26, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output