0% found this document useful (0 votes)
129 views3 pages

Subarray Sum Equals K in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views3 pages

Subarray Sum Equals K in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subarray Sum Equals K

Prefix Sum and Hash Map Solution in C++


Achraf Mahdi MAJIDI
majidiachrafmahdi@[Link]
August 8, 2025

1 Introduction and Motivation


The ”Subarray Sum Equals K” problem is a fundamental example of using
prefix sums and hashing for efficient subarray enumeration. It frequently
appears in interviews and algorithm courses, illustrating how linear-time al-
gorithms can be designed for sum-based subarray queries.

2 Problem Statement
Given an array of integers nums and an integer k, return the total number
of subarrays whose sum equals k. A subarray is a contiguous non-empty
sequence within the array.
Examples:
• Input: nums = [1,1,1], k = 2
Output: 2
• Input: nums = [1,2,3], k = 3
Output: 2
Constraints:
• 1 ≤ [Link] ≤ 2 × 104
• −1000 ≤ nums[i] ≤ 1000
• −107 ≤ k ≤ 107

1
3 Algorithm and Approach
Naively, checking all possible subarrays for sum k would require O(n2 ) time.
The key optimization uses prefix sums with a hash map:

• The running prefix sum at index i is Si = nums[0] + ... + nums[i].

• For each index i, if there exists a prefix sum Sj such that Si − Sj = k,


then the subarray (j + 1, ..., i) sums to k.

• Store counts of all prefix sums encountered so far in a hash map.

• For each step, add to the answer the count of Si − k previously seen.

This captures all subarrays ending at i with sum k in constant time per
index.

4 C++ Implementation

Listing 1: Prefix sum and hash map solution for Subarray Sum Equals K
1 class Solution {
2 public :
3 int subarraySum ( vector < int >& nums , int k ) {
4 int count = 0;
5 unordered_map < int , int > prefixSumCount ;
6 int prefixSum = 0;
7 prefixSumCount [0] = 1;
8 int n = nums . size () ;
9 for ( int i = 0; i < n ; i ++) {
10 prefixSum = prefixSum + nums [ i ];
11 if ( prefixSumCount . find ( prefixSum - k ) !=
prefixSumCount . end () ) {
12 count += prefixSumCount [ prefixSum - k ];
13 }
14 prefixSumCount [ prefixSum ]++;
15 }
16 return count ;
17 }
18 };

2
5 Complexity Analysis
Time Complexity: O(n)
Each index is visited once, and all hash map operations are amortized O(1).
Space Complexity: O(n)
The hash map may store up to n distinct prefix sums.

6 Testing Outcomes
This method works efficiently for:

• Arrays containing positive, negative, and zero values.

• Multiple subarrays with the same sum across the array.

• Edge cases (all elements are 0, k = 0, single-element edge cases).

• Large input sizes up to 2 × 104 elements.

7 Reflections
This problem exemplifies how prefix sum transformations and hash maps can
accelerate subarray counting and sum matching tasks. The logic generalizes
to a wide class of balance and sum-based array problems.

8 Conclusion
The prefix sum with hash map solution reduces a naive quadratic approach
to linear time, making it optimal and suitable for large-scale datasets and
efficient implementation in practice.

Prepared by: Achraf Mahdi MAJIDI


Email: majidiachrafmahdi@[Link]

You might also like