简体   繁体   中英

JavaScript challenge - Sherlock and array

I got the following challenge in interview, with some constraints.

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. Formally, find an i , such that, A1+A2...A(i−1)=A(i+1)+A(i+2)...AN .

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 .

Constraints

1≤T≤10

1≤N≤10^5

1≤Ai≤2×10^4

1≤i≤N

I have solved it but it's failing in some test cases, I want to know the pitfall of my coding. I have spent almost 4-5 hours but unable to solve it.

My solution is -

function processData(input) {
    input = input.split('\n');
    var counter=0;
    var sum = function(n){
        var r=[];
        for(var k=0;k<n.length;k++){
            if(!isNaN(n[k])) {
                if(n[k] >= 1 && n[k] <= (2 * Math.pow(10,4))){
                    r.push(n[k].trim());
                }
            } 
        }
        return r.reduce(function(a, b) { return Number(a) + Number(b); }, 0);
    }
    for(var i=2;i<=input.length;i+=2){
        var ret='NO';
        if(counter<=10){
            input[i] = input[i].split(' ');
            if(input[i].length <= Math.pow(10,5) &&   input[i-1] <= input[i].length && input[i-1] >= 1){
                for(var j=0;j<input[i].length;j++){
                    if(sum(input[i].slice(0,j)) ===  sum(input[i].slice(j+1,input[i].length))){
                        ret = 'YES';
                        break;
                    }
                }
            }
        }
        counter++;
        console.log(ret);
    };

} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Challenge link - https://www.hackerrank.com/challenges/sherlock-and-array

I can't easily write code on my phone, but here is the idea of my solution. I'll make a proper edit once back on a keyboard.

Let's admit the parsing of input file is trivial. Then you just have to write a function returning yes or no for a single array.

Step 1: Reduce the array to get the total sum of it's elements: TotalSim

Step 2: Loop on the array and maintain the partial sum of the elements: LeftSum

Step 3: If LeftSum === TotalSum - LeftSum return yes

STEP 4: End of the array: Return false

Please not that integers in javascript are exact until 2^53 -1, meaning that your constraints guarantee no overflow can occur

iterate through cases, then look for first element in each case wether it complies or not - run reduce on each side of the element and compare results until finds a match or runs out of elements.

this should work:

let test = input => input
     .map(line => line
         .some((el, index) => line.slice(0, index).reduce((p, c) => p + c, 0)
           === line.slice(index - line.length + 1).reduce((p, c) => p + c, 0)))
     .map(result => result ? 'YES' : 'NO');

test(cases); // outputs array of YESs and NOs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM