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 have spend almost 4-5 hr 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);
});
Aucun commentaire:
Enregistrer un commentaire