πDay 8. Subarrays with Sum K π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an unsorted array of integers, find the number of continuous subarrays having a sum exactly equal to a given number k.
π Example Walkthrough:
Input:
arr = [10, 2, -2, -20, 10], k = -10Output:
3Explanation: Subarrays: arr[0...3], arr[1...4], and arr[3...4] have a sum exactly equal to -10.
Input:
arr = [9, 4, 20, 3, 10, 5], k = 33Output:
2Explanation: Subarrays: arr[0...2] and arr[2...4] have a sum exactly equal to 33.
Input:
arr = [1, 3, 5], k = 0Output:
Explanation: No subarray has a sum of 0.
Constraints:
$(1 \leq \text{arr.size()} \leq 10^5)$
$(-10^3 \leq \text{arr[i]} \leq 10^3)$
$(-10^7 \leq k \leq 10^7)$
π― My Approach:
To solve this problem efficiently:
Prefix Sum with Hash Map:
Maintain a running sum (
sum) as you traverse the array.Use a hash map (
prefixSumCount) to store the count of prefix sums encountered so far.For each element, check if the difference
sum - kexists in the hash map. If it does, it means there is a subarray ending at the current index with a sum equal tok.
Increment Hash Map:
Add the current running sum to the hash map or increment its count if it already exists.
Count Matching Subarrays:
Increment the count by the number of times
sum - khas been encountered so far.
Final Answer:
The variable
countwill hold the number of subarrays with a sum equal tok.
π Time and Auxiliary Space Complexity
Expected Time Complexity: (O(n)), as we traverse the array once and perform (O(1)) operations for each element.
Expected Auxiliary Space Complexity: (O(n)), to store the hash map containing prefix sums.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
β Star this repository if you find it helpful or intriguing! β
πVisitor Count
Last updated