Skip to content
Advertisement

A very big sum – Hacker Rank

I am trying to solve “A very big sum” challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}

Second Solution

function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}

But none of them work and I donĀ“t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

Advertisement

Answer

sum += i; should be sum += ar[i];

Also return sum

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}

Also reducer function should be like

function a(ar){
  let sum = (accumulator, currentValue) => accumulator + currentValue;
  return ar.reduce(sum);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement