kennymkchan / interview-questions-in-javascript

A mostly reasonable collection of technical software development interview questions solved in Javascript
MIT License
3.61k stars 441 forks source link

Question 1.2 for loop missing a return keyword #31

Closed misstonbon closed 5 years ago

misstonbon commented 6 years ago
function findMissingNumber(arrayOfIntegers, upperBound, lowerBound) {
  // Iterate through array to find the sum of the numbers
  var sumOfIntegers = 0;
  for (var i = 0; i < arrayOfIntegers.length; i++) {
      return sumOfIntegers += arrayOfIntegers[i];  <---- this is the missing return keyword
  }

  // Find theoretical sum of the consecutive numbers using a variation of Gauss Sum.
  // Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2];
  // N is the upper bound and M is the lower bound

  upperLimitSum = (upperBound * (upperBound + 1)) / 2;
  lowerLimitSum = (lowerBound * (lowerBound - 1)) / 2;

  theoreticalSum = upperLimitSum - lowerLimitSum;

  return theoreticalSum - sumOfIntegers;
} 
kennymkchan commented 6 years ago

Hi @misstonbon, from quick glance, it would seem that the function will be exited on the first attempt into the for loop, and the rest of the logic will not be initiated. Are you able to explain why you think a return is missing?

misstonbon commented 6 years ago

Hello, I have indicated the missing return keyword above. Thanks for providing good interview prep questions.