- Practice
- Algorithms
- Search
- Sherlock and Array
- Discussions

# Sherlock and Array

# Sherlock and Array

+ 0 comments For the test cases which contains a

**single element**, make sure that you print**YES**, otherwise you will fail the Test #6. I think it is a huge mistake of the author, because it is not specified at all!For example for input:

`1`

`1`

`1`

Make sure your answer is:

`YES`

+ 0 comments The way to do it in O(n) time is to take advantage of the fact that the right and left sides will always contain all the elements except for the current one. So when looping left to right, if one sets the right to contain the sum of all the elements in the array save the first (depends on your implementation), and the left to start off as zero, they can go through the entire array adding the previous element to the left and subtracting the current element from the right then comparing. It becomes a matter of a very simple loop that contains two add/subtract operations and the comparison, and it will only loop over the array one time.

+ 0 comments python 3 code, easy to understand :) . It takes linear time

def solve(a): # Complete this function summy=sum(a) l=len(a) lefty=0 for i in range(len(a)): current=a[i] summy-=current if lefty==summy: return 'YES' lefty+=current return 'NO'

+ 0 comments Hello friends,

Sherlock and Array hackerrank problem can be solved easily by deriving a linear equation. The complexity of Sherlock and Array hackerrank solution is O(n)

If interested to know more about the generic algorithm in details-

click here for the

**video explanation of generic algorithm**with complexity analysis.or you can click on the image too to follow youtube tutorial.

**Here is the working solution:-****source code :**static String balancedSums(List<Integer> arr) { int x = 0; int sum = 0; for (int a : arr) { sum += a; } for (int y : arr) { if (2 * x == sum - y) { return "YES"; } x = x + y; } return "NO"; }

Would really appreciate your feedback like, dislike , comment etc. on my video.

# Do not forget to upvote, if you find it useful.

+ 0 comments I have used an implementation which takes care of that test case by itself. Here is a Java implementation which passes all test case in o(n) time.

private static String balancedSums(List<Integer> arr) { int sum = 0; // get sum of all array index. for (int i = 0; i < arr.size(); i++){ sum += arr.get(i); } // initially left sum is zero. int leftSum = 0; for (int i = 0; i < arr.size(); i++) { //if left sum equals right sum print yes. if (leftSum == (sum - leftSum - arr.get(i))) { return "YES"; } leftSum += arr.get(i); } return "NO"; }

Sort 756 Discussions, By:

Please Login in order to post a comment