U

47. Count Subarrays with Sum Equal to Target

Med.

Problem Description

Given an array of NN integers and a target KK, count the total number of continuous subarrays whose sum equals KK.

Input Format

  • •Line 1: Two space-separated integers NN and KK (1≤N≤1051 \le N \le 10^5).
  • •Line 2: NN space-separated integers A1,…,ANA_1, \dots, A_N.

Output Format

Print the total count of contiguous subarrays whose sum equals KK.

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