Sherlock and Array

  • + 0 comments

    Java solution using only one loop.

    Time complexity: O(n)

    Space complexity: O(1)

    I found a test case that HackerRank ignores: inputs like "0000...a" should return "YES", but they incorrectly accept "NO" as a valid result.

    public static String balancedSums(List<Integer> arr) {
            int n = arr.size();
            arr.add(0,0);
            arr.add(0);
            int i = 0;
            int j = n+1;
            int cSumL = arr.get(i);
            int cSumR = arr.get(j);
            while(j>=i+2){
                if(cSumL>cSumR){
                    j--;
                    cSumR += arr.get(j);    
                }else if(cSumL<cSumR){
                    i++;
                    cSumL += arr.get(i);
                }else{
                    if(j==i+2){
                        return "YES";
                    }else{
                        if(arr.get(j-1)==0){
                            j--;
                        }else{
                            i++;
                            cSumL += arr.get(i);
                            
                        }
                    }
                }
    
            }
            return "NO";
        }