Sherlock and Array

Sort by

recency

|

153 Discussions

|

  • + 0 comments

    Javascript

    function balancedSums(arr) {
        // Write your code here    
        var leftSum = 0
        var rightSum = arr.reduce((a, b) => a + b)
        
        for(var i = 0; i < arr.length; i++){
            leftSum = i == 0 ? 0 : leftSum + arr[i - 1]
            rightSum = i == arr.length - 1 ? 0 : rightSum - arr[i]                
            if (leftSum == rightSum){
                return 'YES'
            }        
        }
        return 'NO'
    }
    
  • + 0 comments

    My Solution using javascript

    function balancedSums(arr) {
        // Write your code here
        let totalSum = arr.reduce((acc, numb) => acc + numb, 0)
        let leftSum = 0;
        
        for(let i = 0; i < arr.length; i++){
            const rightSum = totalSum - leftSum - arr[i]
            
            if(leftSum === rightSum){
                return "YES"
            }
            
            leftSum += arr[i]
        }
        return "NO"
    }
    
  • + 1 comment

    how can [2 0 0 0] has expected answer "YES"?

    • + 0 comments

      The first element can be the split. Then leftsum will be 0(since there is no element on the left of the first one) and A[1]+A[2]+A[3] = 0

  • + 0 comments

    short c++ solution using prefix sums - i-th element is the sum of all the previous elements + the i-th element of arr.

    string balancedSums(vector<int> arr) {
        bool ok = false;
        
        int n = arr.size();
        vector<int> a(n+1,0);
        
        for (int i = 1; i <= n; i++) {
            a[i] = a[i-1] + arr[i-1];
        }
        
        for (int i = 1; i < n; i++) {
            int l = a[i-1];
            int r = a[n]-a[i];
            ok |= (r==l);
        }
        return ok or n==1 ? "YES" : "NO";
    }
    
  • + 1 comment
    from functools import reduce
    
    def balancedSums(arr):
        sum_arr = sum(arr)
        return 'YES' if (reduce(lambda a, b: a + (b if a <= sum_arr // 2 else 0), arr) == reduce(lambda a, b: a + (b if a <= sum_arr // 2 else 0), reversed(arr))) else 'NO'
    
    • + 0 comments

      This code gives 'YES' for the following input. But there is no index to satisfy the condition. The right answer should be "NO". 1 4 1 1 1 1