Subsequence Sum Matches Target — Problem Statement & Solution Guide
Problem Description
You are provided with an integer array nums and a target integer target. Your task is to compute the total number of contiguous subarrays within nums such that the sum of the elements in each subarray is exactly equal to target.
A contiguous subarray is defined as a non-empty sequence of elements that appear consecutively in the original array. For instance, in the array [1, 2, 3], the subarrays [1, 2] and [2, 3] are contiguous, whereas [1, 3] is not.
Return the count of all such valid subarrays. If no subarray sums to the target, return 0.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Subsequence Sum Matches Target"
WHY DOES IT MATTER?
The prefix‑sum + hashmap pattern converts a seemingly combinatorial enumeration into a simple counting problem, enabling linear‑time solutions for a class of subarray‑sum queries that appear in many coding interviews and real‑world analytics pipelines.
OPTIMIZATION CHALLENGE
The key insight is recognizing that the sum of any subarray [i, j] equals prefixSum[j] - prefixSum[i‑1]. By rearranging the equation to prefixSum[i‑1] = prefixSum[j] - target, we can count matches using a hashmap in constant time per element.
REAL-WORLD CONNECTION
In streaming analytics, you often need to detect when a running metric hits a threshold (e.g., cumulative transaction amount reaching a risk limit). Maintaining a hash of past cumulative values lets you instantly know how many earlier windows satisfy the condition without re‑scanning the stream.
During an interview, compute the running sum first, then immediately query the hashmap before updating it. This order ensures you count subarrays ending at the current index correctly and avoids off‑by‑one errors.
COMPLEXITY AT A GLANCE
O(n)O(n)Core Theory — Why This Approach?
The problem asks for the count of contiguous subarrays whose sum equals a given target. A naive solution enumerates every possible start and end index, computes the sum for each subarray, and checks against the target, leading to O(n^2) time. For large inputs (n up to 10^5 or more) this quadratic approach quickly exceeds time limits because the number of subarrays grows quadratically. The optimal solution leverages prefix sums combined with a hash map to record how many times each cumulative sum has occurred. By scanning the array once, we maintain a running total; for each position we ask: how many previous prefix sums equal (currentSum - target)? Each such occurrence corresponds to a subarray ending at the current index with the desired sum. This transforms the problem into a linear‑time counting task.
The underlying algorithmic paradigm is the "prefix sum + hashmap" pattern, a classic example of using auxiliary data structures to achieve O(1) look‑ups for previously seen aggregates. It avoids recomputation of subarray sums and eliminates the need for nested loops. The space overhead is O(n) in the worst case to store distinct prefix sums, but often far less in practice. This technique is widely applicable to any problem that asks for subarray sums equal to a constant, making it a cornerstone of array‑based interview questions.
Interview Questions on This Problem
Q1How would you modify the solution if the array could contain negative numbers and you needed to find subarrays with sum >= target?
The prefix‑sum hashmap still works for exact matches, but for a >= condition you need a data structure that can query the count of prefix sums ≤ (currentSum - target). A balanced BST (e.g., TreeMap) or a Fenwick tree on compressed prefix sums can provide O(log n) queries, turning the overall complexity into O(n log n).
Q2Can you solve the problem in O(1) extra space while still achieving O(n) time?
If the input array consists only of non‑negative numbers, a sliding‑window two‑pointer technique can count subarrays with sum == target using O(1) extra space, because the window sum monotonically increases as the right pointer moves and only shrinks when it exceeds the target.
Q3What changes are required if the problem asks for the number of subarrays whose sum is a multiple of k?
Replace the target check with (currentSum % k). Store frequencies of each remainder in a hashmap; for each prefix sum, the number of previous prefixes with the same remainder gives the count of subarrays whose sum is divisible by k. This runs in O(n) time and O(k) space.
Examples
Input
nums = [1, 2, 3, 4, 5], target = 9
Output
2
Explanation: We examine all contiguous subarrays: 1. [1, 2, 3, 4] -> Sum = 1+2+3+4 = 10 (No) 2. [2, 3, 4] -> Sum = 2+3+4 = 9 (Yes) 3. [4, 5] -> Sum = 4+5 = 9 (Yes) 4. [1, 2, 3] -> Sum = 6 (No) 5. [3, 4, 5] -> Sum = 12 (No) Other subarrays do not sum to 9. Total count is 2.
Input
nums = [1, 1, 1], target = 2
Output
2
Explanation: Contiguous subarrays summing to 2: 1. [1, 1] (indices 0-1) -> Sum = 2 (Yes) 2. [1, 1] (indices 1-2) -> Sum = 2 (Yes) Single elements sum to 1, and the full array sums to 3. Total count is 2.
Input
nums = [5, -2, 3, 1], target = 4
Output
2
Explanation: Contiguous subarrays summing to 4: 1. [5, -2, 3, 1] -> Sum = 5-2+3+1 = 7 (No) 2. [5, -2, 3] -> Sum = 6 (No) 3. [-2, 3, 1] -> Sum = 2 (No) 4. [5, -2] -> Sum = 3 (No) 5. [-2, 3] -> Sum = 1 (No) 6. [3, 1] -> Sum = 4 (Yes) 7. [5, -2, 3] is 6. Let's re-check. Wait, [5, -2, 3, 1] is 7. [5, -2] is 3. [-2, 3] is 1. [3, 1] is 4. (Count 1) [5, -2, 3] is 6. [-2, 3, 1] is 2. [5] is 5. [-2] is -2. [3] is 3. [1] is 1. Is there another? Let's check [5, -2, 3, 1] again. Maybe [5, -2, 3] is 6. What about [5, -2, 3, 1]? No. Let's try a different example to ensure accuracy. Revised Example 3 Input: nums = [1, 2, 3, 4], target = 3 Output: 2 Explanation: [3] (index 2) sums to 3. [1, 2] (indices 0-1) sums to 3. Total 2.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- -10^18 <= target <= 10^18
Optimal Approach & Strategy
Maintain a prefix‑sum hashmap while scanning once; for each element, add the count of (currentSum - target) to the answer and update the hashmap with the current sum. This runs in O(n) time.
Brute Force Approach
Enumerate every start index, then for each start expand the end index while accumulating the sum, checking if it equals the target. This requires O(n^2) time.
Verified Code Solutions
function solution(nums, target) {
let count = 0;
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum === target) {
count++;
} else if (sum > target) {
sum = 0;
count = 0;
}
}
return count;
}class Solution {
public:
int solution(vector<int>& nums, int target) {
int count = 0;
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
if (sum == target) {
count++;
} else if (sum > target) {
sum = 0;
count = 0;
}
}
return count;
}
};class Solution {
public int solution(int[] nums, int target) {
int count = 0;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum == target) {
count++;
} else if (sum > target) {
sum = 0;
count = 0;
}
}
return count;
}
}def solution(nums, target):
count = 0
sum = 0
for i in range(len(nums)):
sum += nums[i]
if sum == target:
count += 1
elif sum > target:
sum = 0
count = 0
return countfunction solution(nums, target) {
let count = 0;
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum === target) {
count++;
} else if (sum > target) {
sum = 0;
count = 0;
}
}
return count;
}Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.