VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-every-subarray-of-even-length-has-sum-0/

⇱ Check if every Subarray of even length has sum 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if every Subarray of even length has sum 0

Last Updated : 23 Jul, 2025

Given an array A[ ] of size N, the task is to check if the sum of every even-sized subarray is 0 or not.

Examples:

Input: N = 4, A[] = {8, -8, 7, 9}
Output: NO
Explanation: Sum of subarray {7, 9} is not 0.

Input: N = 2, A[] = {0, 0}
Output: YES
Explanation: The only possible even length subarray is {0, 0} and its sum is 0.

Naive Approach: The basic way to solve the problem is as follows:

Generate all possible subarrays,then choose all even length subarray from that.Then, check if everytime its sum  is 0 or not. If anytime it's sum is not zero then return "NO" else return "YES".

Steps to implement-

  • Run two loops to find all subarrays
  • Simultaneously calculate the length of all subarray
  • If any subarray's length is even then find its sum
  • If anyone subarray of even length has non-zero sum then print "NO" else print "YES"

Code-


Output
NO

Time Complexity: O(N3), because of two nested loops to find all subarray and a third loop to find the sum of all elements of the subarray
Auxiliary Space: O(1), because no extra space has been used

Efficient Approach: To solve the problem follow the below idea:

The idea is to check the complete array once for all possible subarrays of length 2 because all other even sized subarrays of length greater than 2 can be made by combining subarrays of length 2. So if all subarrays of length 2 have sum 0, all other even sized subarrays will also have sum 0.

Follow the steps mentioned below to implement the idea:

  • Start iterating from i = 1 to N-1:
    • Check if the sum of A[i] and A[i-1] is 0 or not.
    • If it is not 0, return the answer as "NO" and no need to calculate further.
  • If the iteration is over and the condition is satisfied for all the subarrays, return "YES" as the required answer.

Below is the implementation of the above approach.


Output
NO

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment