#K92357. Subarray Sum Equals k

    ID: 38179 Type: Default 1000ms 256MiB

Subarray Sum Equals k

Subarray Sum Equals k

Given an integer array \( nums \) and an integer \( k \), your task is to find the total number of contiguous subarrays that sum up to \( k \). A subarray is a contiguous sequence of elements within an array.

You can use the prefix sum technique: if \( S_i \) is the sum of the first \( i \) elements, then a subarray from index \( i+1 \) to \( j \) has a sum of \( S_j - S_i \). Thus, the problem reduces to finding the number of pairs \( (i, j) \) such that \( S_j - S_i = k \).

inputFormat

The input is given via standard input (stdin) in the following format:

  • The first line contains an integer \( n \) representing the number of elements in the array.
  • The second line contains \( n \) space-separated integers representing the elements of the array. If \( n = 0 \), this line will be empty.
  • The third line contains an integer \( k \), the target sum.

outputFormat

Output via standard output (stdout) a single integer that represents the total number of contiguous subarrays whose sum equals \( k \).

## sample
3
1 1 1
2
2