#K44962. Zero Sum Subarray
Zero Sum Subarray
Zero Sum Subarray
You are given an array of integers. Your task is to determine whether there exists a non-empty contiguous subarray whose sum is zero.
Formally, given an array \(b = [b_1, b_2, \dots, b_m]\), check if there exists indices \(i\) and \(j\) with \(1 \leq i \leq j \leq m\) such that \[ b_i + b_{i+1} + \cdots + b_j = 0. \]
If such a subarray exists, print YES
, otherwise print NO
.
This is a classical problem that can be efficiently solved using prefix sums and a hash set to track previously seen sums.
inputFormat
The input is read from standard input.
- The first line contains a single integer \(T\) denoting the number of test cases.
- Then for each test case:
- The first line contains an integer \(m\) indicating the number of elements in the array.
- The second line contains \(m\) space-separated integers representing the array \(b\).
outputFormat
For each test case, output a single line containing either YES
or NO
(without quotes), indicating whether a zero-sum subarray exists.
3
5
4 -3 2 1 6
4
1 2 -2 5
3
3 4 5
YES
YES
NO
</p>