Sherlock and Array

  • + 0 comments

    My Java solution with O(n) time complexity and O(1) space complexity:

    public static String balancedSums(List<Integer> arr) {
            // goal: find element of arr where sum of elements to left equals sum of elements to the right
            if(arr.size() == 1) return "YES"; //left = 0 = right
            
            int totalSum = arr.stream().mapToInt(Integer::intValue).sum();
            int leftSum = 0;
    
            for (int i = 0; i < arr.size(); i++) {
                int rightSum = totalSum - leftSum - arr.get(i);
                if (leftSum == rightSum) return "YES";
                leftSum += arr.get(i);
            }
            return "NO";
        }