#K83902. Subarray Sum Equals Target

    ID: 36300 Type: Default 1000ms 256MiB

Subarray Sum Equals Target

Subarray Sum Equals Target

You are given an array of n integers and a target value T. Your task is to determine whether there exists a contiguous subarray (i.e. a subarray made of consecutive elements) whose sum is exactly equal to \( T \).

Note: The subarray must contain at least one element. For example, given the array [1, 4, 20, 3, 10, 5] and target 33, the contiguous subarray [20, 3, 10] sums to 33.

This problem can be solved efficiently using prefix sums. The key idea is to compute the cumulative sum as you traverse the array and check if the difference between the current cumulative sum and the target exists in a set of previously seen cumulative sums. Mathematically, if we denote the cumulative sum up to index i as \( S_i \), then we are looking for an index j such that:

\( S_i - S_j = T \)

If such a pair exists, then the subarray from index j+1 to i has a sum equal to \( T \).

inputFormat

The input is read from stdin and includes two lines:

  • The first line contains two space-separated integers: n (the number of elements in the array) and T (the target sum).
  • The second line contains n space-separated integers, representing the elements of the array.

outputFormat

Output a single line to stdout with either True if a contiguous subarray exists with sum equal to T, or False otherwise.

## sample
6 33
1 4 20 3 10 5
True

</p>