BackmediumHashing Uber

Subarray Sum Finder Solution

Problem Statement

Given a log of integer readings and a threshold K, count how many contiguous sub-logs have a total sum exactly equal to K.

Example 1
Input
[1, 2, 3, 4, 5], 6
Output
2

Explanation: Step-by-step: We start with the array [1, 2, 3, 4, 5] and the target sum 6. We use a hashmap to store the cumulative sum and its frequency. We iterate through the array, and for each element, we check if the hashmap contains the cumulative sum minus the current element. If it does, we increment the count by the frequency of the cumulative sum minus the current element. We update the hashmap with the new cumulative sum and its frequency. Finally, we return the count of subarrays with sum 6.

Example 2
Input
[5, 5, 10], 10
Output
1

Explanation: Step-by-step: We start with the array [5, 5, 10] and the target sum 10. We use a hashmap to store the cumulative sum and its frequency. We iterate through the array, and for each element, we check if the hashmap contains the cumulative sum minus the current element. If it does, we increment the count by the frequency of the cumulative sum minus the current element. We update the hashmap with the new cumulative sum and its frequency. Finally, we return the count of subarrays with sum 10.

Constraints

  • 1 <= n <= 2 * 10^4
  • -1000 <= arr[i] <= 1000
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free