ExamAdda Logo

Subarray Sum Equals K

Medium

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

1 <= nums.length <= 20000
-1000 <= nums[i] <= 1000
-10^7 <= k <= 10^7

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

ExamAdda Technical Review Team

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.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output