|
U
Pro47. Count Subarrays with Sum Equal to Target
Med.
Problem Description
Given an array of N integers and a target K, count the total number of continuous subarrays whose sum equals K.
Input Format
- •Line 1: Two space-separated integers N and K (1≤N≤105).
- •Line 2: N space-separated integers A1,…,AN.
Output Format
Print the total count of contiguous subarrays whose sum equals K.
Example 1:
Input:
3 2 1 1 1
Output:
2
Explanation: Subarrays [1, 1] at index (0,1) and (1,2) both sum to 2.
Example 2:
Input:
3 3 1 2 3
Output:
2
Explanation: [1, 2] and [3] both sum to 3.
Example 3:
Input:
4 0 0 0 0 0
Output:
10
Explanation: All 4*(4+1)/2 = 10 subarrays sum to 0.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit