Snap Inc Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
function sub(a, k){
if(!Array.isArray(a) || Number(k) === NaN){
throw new Error('Wrong input');
}
let map = new Map();
let sum = 0;
for(let i=0; i < a.length; i++){
sum += a[i];
let diff = sum - k;
if(diff === k){
return `0 to ${i}`;
}
let history = map.get(diff);
if(history !== undefined){
return `${history + 1} to ${i}`;
}
else{
map.set(sum, i);
}
}
return 'not found';
}
let aa = [8,5,1,4,-10,66];
console.log(sub(aa, 0));
let aa2 = [12,3,4,-500, 300, 20, 180, 40, 9];
console.log(sub(aa2, 0));
let
input = [1, 2, 3, 5, -10],
currStart = 0,
currEnd = 0,
prevSum = 0,
currSum = 0;
for(let i = 0; i < input.length; i++) {
currSum = input[i];
for(let j = i + 1; j < input.length; j++) {
currSum += input[j];
if (currSum > prevSum) {
currStart = i;
prevSum = currSum;
currEnd = j;
}
}
}
console.log("Array from index " + (currStart + 1) + " to index " + (currEnd + 1));
- verma.ius April 25, 2017