![]() |
VOOZH | about |
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-
Code-
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:
Below is the implementation of the above approach.
NO
Time Complexity: O(N)
Auxiliary Space: O(1)