Thursday, October 20, 2022
HomeWordPress DevelopmentVerify if each Subarray of even size has sum 0

Verify if each Subarray of even size has sum 0


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given an array A[ ] of measurement N, the duty is to verify if the sum of each even-sized subarray is 0 or not.

Examples:

Enter: N = 4, A[] = {8, -8, 7, 9}
Output: NO
Rationalization: Sum of subarray {7, 9} will not be 0.

Enter: N = 2, A[] = {0, 0}
Output: YES
Rationalization: The one doable even size subarray is {0, 0} and its sum is 0.

Naive Method: The fundamental strategy to resolve the issue is as follows:

Generate all doable even size subarrays and verify if sum is 0 or not and return “YES” or “NO” accordingly.

Time Complexity: O(N2)
Auxiliary House: O(1)

Environment friendly Method: To resolve the issue comply with the under thought:

The thought is to verify the whole array as soon as for all doable subarrays of size 2 as a result of all different evn sized subarrays of size higher than 2 could be made by combining subarrays of size 2. So if all subarrays of size 2 have sum 0, all different even sized subarrays will even have sum 0.

Observe the steps talked about under to implement the thought:

  • Begin iterating from i = 1 to N-1:
    • Verify if the sum of A[i] and A[i-1] is 0 or not.
    • If it’s not 0, return the reply as “NO” and no must calculate additional.
  • If the iteration is over and the situation is glad for all of the subarrays, return “YES” because the required reply.

Beneath is the implementation of the above strategy.

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

string resolve(int N, int A[])

{

    int ans = 1;

  

    

    

    for (int i = 1; i < N; i++) {

        if (A[i] + A[i - 1] != 0) {

            ans = 0;

            break;

        }

    }

    if (ans)

        return "YES";

    return "NO";

}

  

int predominant()

{

    int A[] = { 8, -8, 7, 9 };

    int N = sizeof(A) / sizeof(A[0]);

  

    

    cout << resolve(N, A);

    return 0;

}

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments