Open In App

Check if every Subarray of even length has sum 0

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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-

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if the subarrays
// satisfying the conditions can be formed
string solve(int N, int A[])
{
     
   //Find all subarray
   for(int i=0;i<N;i++){
       //To store length of subarray
       int length=0;
       for(int j=i;j<N;j++){
           //Increment the length
           length++;
            
           //When subarray has even length
           if(length%2==0){
               
              //To store sum of all element of subarray
              int sum=0;
               
              //Find sum of all element of subarray
              for(int k=i;k<=j;k++){
                  sum+=A[k];
              }
               
              //when any one subarray of even length
              //does not have 0 sum
              if(sum!=0){
                  return "NO";
              }
           }
       }
   }
   //When every subarray of even length has
   //sum 0
   return "YES";
}
 
// Driver code
int main()
{
    int A[] = { 8, -8, 7, 9 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << solve(N, A);
    return 0;
}


Java




public class GFG {
 
    // Function to find if the subarrays
    // satisfying the conditions can be formed
    static String solve(int N, int[] A) {
 
        // Find all subarrays
        for (int i = 0; i < N; i++) {
            // To store the length of the subarray
            int length = 0;
            for (int j = i; j < N; j++) {
                // Increment the length
                length++;
 
                // When the subarray has even length
                if (length % 2 == 0) {
 
                    // To store the sum of all elements of the subarray
                    int sum = 0;
 
                    // Find the sum of all elements of the subarray
                    for (int k = i; k <= j; k++) {
                        sum += A[k];
                    }
 
                    // When any one subarray of even length
                    // does not have a sum of 0
                    if (sum != 0) {
                        return "NO";
                    }
                }
            }
        }
        // When every subarray of even length has
        // a sum of 0
        return "YES";
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] A = {8, -8, 7, 9};
        int N = A.length;
 
        // Function Call
        System.out.println(solve(N, A));
    }
}


Python3




# Function to find if the subarrays
# satisfying the conditions can be formed
def solve(N, A):
    # Find all subarray
    for i in range(N):
       
        # To store length of subarray
        length = 0
        for j in range(i, N):
            # Increment the length
            length += 1
            #When subarray has even length
            if length % 2 == 0:
                #To store sum of all element of subarray
                _sum = 0
                for k in range(i, j+1):
                    _sum += A[k]
                 
                # when any one subarray of even length
                # does not have 0 sum
                if _sum != 0:
                    return "NO"
    # When every subarray of even length has
    # sum 0
    return "YES"
 
   
# Test case
A = [8, -8, 7, 9]
N = len(A)
print(solve(N, A))


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class Gfg{
    // Function to find if the subarrays
    // satisfying the conditions can be formed
    static string solve(int N, int[] A)
    {
         
       //Find all subarray
       for(int i=0;i<N;i++){
           //To store length of subarray
           int length=0;
           for(int j=i;j<N;j++){
               //Increment the length
               length++;
                
               //When subarray has even length
               if(length%2==0){
                   
                  //To store sum of all element of subarray
                  int sum=0;
                   
                  //Find sum of all element of subarray
                  for(int k=i;k<=j;k++){
                      sum+=A[k];
                  }
                   
                  //when any one subarray of even length
                  //does not have 0 sum
                  if(sum!=0){
                      return "NO";
                  }
               }
           }
       }
       //When every subarray of even length has
       //sum 0
       return "YES";
    }
     
    // Driver code
    static void Main(string[] args)
    {
        int[] A = { 8, -8, 7, 9 };
        int N = A.Length;
     
        // Function Call
        Console.WriteLine(solve(N, A));
    }
}


Javascript




// Function to find if the subarrays
// satisfying the conditions can be formed
function solve(N, A) {
    //Find all subarray
    for (let i = 0; i < N; i++) {
         
        //To store length of subarray
        let length = 0;
        for (let j = i; j < N; j++) {
             
            //Increment the length
            length++;
             
            //When subarray has even length
            if (length % 2 === 0) {
                 
                //To store sum of all element of subarray
                let sum = 0;
                //Find sum of all element of subarray
                for (let k = i; k <= j; k++) {
                    sum += A[k];
                }
                
                //when any one subarray of even length
                //does not have 0 sum
                if (sum !== 0) {
                    return "NO";
                }
            }
        }
    }
   //When every subarray of even length has
   //sum 0
    return "YES";
}
 
const A = [8, -8, 7, 9];
const N = A.length;
 
console.log(solve(N, A));


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.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if the subarrays
// satisfying the conditions can be formed
string solve(int N, int A[])
{
    int ans = 1;
 
    // Loop to check if all subarrays
    // of size 2 has sum 0
    for (int i = 1; i < N; i++) {
        if (A[i] + A[i - 1] != 0) {
            ans = 0;
            break;
        }
    }
    if (ans)
        return "YES";
    return "NO";
}
 
// Driver code
int main()
{
    int A[] = { 8, -8, 7, 9 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << solve(N, A);
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG {
    // Function to find if the subarrays
    // satisfying the conditions can be formed
    public static String solve(int N, int A[])
    {
        int ans = 1;
 
        // Loop to check if all subarrays
        // of size 2 has sum 0
        for (int i = 1; i < N; i++) {
            if (A[i] + A[i - 1] != 0) {
                ans = 0;
                break;
            }
        }
        if (ans != 0)
            return "YES";
        return "NO";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 8, -8, 7, 9 };
        int N = A.length;
 
        // Function Call
        System.out.print(solve(N, A));
    }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python code to implement the approach
 
# Function to find if the subarrays
# satisfying the conditions can be formed
def solve(N, A):
    ans = 1
     
    # Loop to check if all subarrays
    # of size 2 has sum 0
    for i in range(1, N):
        if A[i] + A[i - 1] != 0:
            ans = 0
            break
 
    if ans:
        return "YES"
    return "NO"
 
# Driver code
A = [8, -8, 7, 9]
N = len(A)
 
# Function Call
print(solve(N, A))
 
# This code is contributed by garg28harsh.


C#




// C# implementation
using System;
 
public class GFG {
 
  // Function to find if the subarrays
  // satisfying the conditions can be formed
  static string solve(int N, int[] A)
  {
    int ans = 1;
 
    // Loop to check if all subarrays
    // of size 2 has sum 0
    for (int i = 1; i < N; i++) {
      if (A[i] + A[i - 1] != 0) {
        ans = 0;
        break;
      }
    }
    if (ans == 1)
      return "YES";
    return "NO";
  }
 
  static public void Main()
  {
    int[] A = { 8, -8, 7, 9 };
    int N = A.Length;
 
    // Function Call
    Console.WriteLine(solve(N, A));
 
    // Code
  }
}
 
// this code is contributed by ksam24000


Javascript




// JavaScript code to implement the approach
 
// Function to find if the subarrays
// satisfying the conditions can be formed
const solve = (N, A) => {
    let ans = 1;
 
    // Loop to check if all subarrays
    // of size 2 has sum 0
    for (let i = 1; i < N; i++) {
        if (A[i] + A[i - 1] != 0) {
            ans = 0;
            break;
        }
    }
    if (ans)
        return "YES";
    return "NO";
}
 
// Driver code
 
let A = [8, -8, 7, 9];
let N = A.length;
 
// Function Call
console.log(solve(N, A));
 
// This code is contributed by rakeshsahni


Output

NO






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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads