Sherlock and Array[HackerRank Solution]

1–2 minutes

read

Sherlock and Array[HackerRank Solution]

Problem:

Watson gives Sherlock an array A of length n. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero.

 

Input Format

The first line contains T, the number of test cases. For each test case, the first line contains n, the number of elements in the array A. The second line for each test case contains n space-separated integers, denoting the array A .

 

Output Format

For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.

Sample Input 0

2
3
1 2 3
4
1 2 3 3

Sample Output 0

NO
YES

Explanation 0

For the first test case, no such index exists.
For the second test case, A[0] + A[1] = A[3], therefore index 2 satisfies the given conditions.

 

Code:

#include <bits/stdc++.h>

using namespace std;

string solve(vector < int > a){
 // Complete this function
 int n=a.size();
 int leftsum =0;
 int flag =0;
 int sum =0;
 for(int i=0;i<n;i++)
 {
 sum+= a[i];
 }
 for(int i=0;i<n;i++)
 {
 sum-=a[i];
 if(leftsum == sum)
 {
 flag =1;
 return "YES";
 }
 leftsum+=a[i];
 
 }
 if(flag == 0){
 return "NO";
 }
 return "NO";
}

int main() {
 int T;
 cin >> T;
 for(int a0 = 0; a0 < T; a0++){
 int n;
 cin >> n;
 vector<int> a(n);
 for(int a_i = 0; a_i < n; a_i++){
 cin >> a[a_i];
 }
 string result = solve(a);
 cout << result << endl;
 }
 return 0;
}

Passed all test Cases!

2 responses to “Sherlock and Array[HackerRank Solution]”

  1. I am forever thought about this, thanks for posting.

    Liked by 1 person

Leave a comment