#C13567. Subarray Sum with Fixed Length
Subarray Sum with Fixed Length
Subarray Sum with Fixed Length
You are given an array of integers, an integer n representing the length of a contiguous subarray, and an integer target. Your task is to determine whether there exists a contiguous subarray of length n within the given array such that the sum of its elements is equal to target.
The problem can be formally described as follows. Given an array \(A\) of length \(m\), find if there exists an index \(i\) (with \(0 \leq i \leq m-n\)) such that:
[ \sum_{j=0}^{n-1} A_{i+j} = target ]
If such an index exists, output True
; otherwise, output False
. A sliding window technique can be used to achieve an optimal time complexity of \(O(m)\), because after computing the sum of the first window (first \(n\) elements), the sum of each subsequent window can be computed in constant time by subtracting the element going out of the window and adding the new element coming into the window.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains an integer m representing the number of elements in the array.
- The second line contains m integers separated by spaces.
- The third line contains two integers separated by a space: n (the length of the subarray) and target (the desired sum).
outputFormat
The output should be written to standard output (stdout) and is a single line containing either True
if such a contiguous subarray exists or False
otherwise.
5
1 2 3 4 5
2 3
True