JavaScript frequently asked problem solving question with solution

11 minute read

1. FIND THE LARGEST ELEMENT OF AN ARRAY

There are multiple ways to find out the largest value of an array. One way is to use Math.max() function to find the largest value.

let prices = [10, 13, 14, 16, 18];
console.log(Math.max(...prices)); // 18

But often interviewer may ask you to write a for loop to find the largest value of an array. Let’s do the same exercise with for loop.

const prices = [10, 13, 14, 16, 18];
let max = prices[0];

for (let i = 0; i < prices.length; i++) {
  // You can set a debugger and check how each value are changing
  let element = prices[i];
  if (element > max) {
    max = element;
  }
}
console.log(`The largest value is ${max}`);
// The largest value is 18

Also, we can write a reusable function to find the largest element of an array.

function largestNumber(numbersArray) {
  let max = numbersArray[0];
  for (let i = 0; i < numbersArray.length; i++) {
    let element = numbersArray[i];
    if (element > max) {
      max = element;
    }
  }
  return max;
}
const profit = [7, 12, 15, 18, 20];
console.log(largestNumber(profit)); // 20

2. FIND SUM OF ALL NUMBERS IN AN ARRAY

Like finding the largest number, there are multiple ways to find the sum of all numbers in an array.

We can calculate the sum using for loop:

const sales = [6, 21, 25, 54, 71, 75, 96, 97];

let sum = 0;
for (let i = 0; i < sales.length; i++) {
  let element = sales[i];
  sum = sum + element;
}

console.log(`Total Sales is ${sum}`);
// Total Sales is 445

We can write a function as well:

function getSum(numbersArray) {
  let sum = 0;
  for (let i = 0; i < numbersArray.length; i++) {
    let element = numbersArray[i];
    sum = sum + element;
  }
  return sum;
}

const profit = [45, 65, 68, 12, 3];
console.log('Total: ', getSum(profit)); // 193

Also another way to find the sum is to use reduce higher order function:

const numbers = [2, 42, 54, 56, 68, 75, 82, 85];
const total = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0
);
console.log(total); // 464

3. REMOVE DUPLICATE ITEM FROM AN ARRAY

It is often require to deal with duplicate number, we can remove duplicate from an array in multiple ways.

We can remove duplicates using for loop:

let arrNum = [3, 1, 9, 11, 5, 6, 2, 7, 3, 2, 8];

let uniqueNum = [];
for (let i = 0; i < arrNum.length; i++) {
  let element = arrNum[i]; /* each index element */
  let index = uniqueNum.indexOf(
    element
  ); /* check the element index in uniqueNum */

  if (index == -1) {
    /* when the element is not found in uniqueNum, push will add */
    uniqueNum.push(element);
  }
}
console.log(uniqueNum);
// [ 3, 1, 9, 11, 5, 6, 2, 7,  8 ]

We can write a function like this also:

function findUnique(arrayX) {
  let uniqueNum = [];
  for (let i = 0; i < arrayX.length; i++) {
    let element = arrayX[i];
    let index = uniqueNum.indexOf(element);

    if (index == -1) {
      uniqueNum.push(element);
    }
  }
  return uniqueNum;
}

console.log(findUnique([5, 5, 7, 9, 0, 5, 9, 0, 3]));
// [ 5, 7, 9, 0, 3 ]

Remove duplicate using indexOf and filter:

let arrNum = [3, 1, 9, 11, 5, 6, 2, 7, 3, 2, 8];

let uniqueNum = arrNum.filter((num, index) => {
  return arrNum.indexOf(num) === index;
});

console.log(uniqueNum);
// [ 3, 1, 9, 11, 5, 6, 2, 7,  8 ]

Remove duplicate using includes and forEach:

let arrNum = [3, 1, 9, 11, 5, 6, 2, 7, 3, 2, 8];

let uniqueNum = [];
arrNum.forEach((num) => {
  if (!uniqueNum.includes(num)) {
    uniqueNum.push(num);
  }
});

console.log(uniqueNum);
// [ 3, 1, 9, 11, 5, 6, 2, 7,  8 ]

4. COUNT THE NUMBER OF WORDS IN A STRING

There are lots of ways to count the number of words in a string like using for loop, using regex with string method like replace, split etc.

Let’s solve the problem with for loop first, then I will share a simple solution.

let text =
  'This is a problem solving with counting number of words in a string';

// Target spaces between words
let text =
  'This is a problem solving with counting number of words in a string';

// Target spaces between words
let wordCount = 0;
for (let i = 0; i < text.length; i++) {
  let char = text[i];

  if (char == ' ' && text[i - 1] != ' ') {
    /* text[i - 1] is applied to ignore double spaces */
    wordCount++;
    /* 1 less than expected word count cause there is no space after last word */
  }
}
wordCount++; /* add 1 to fix the prior count */

console.log(`Number of words are ${wordCount}`);
// Number of words are 13

Also we can create a simple function like this to find the number of words:

let text =
  'This is a problem solving with counting number of words in a string';
function wordCounter(str) {
  return str.split(' ').filter((n) => n != '').length;
}

console.log(wordCounter(text)); // 13

5. REVERSE A STRING

This is one of the common javascript problem solving question. There are multiple ways to solve this problem, I will share two solution, one using for loop and another with string method like split, reverse and join.

Using for loop:

let question = 'How to reverse a string in javascript?';
function stringReverser(str) {
  let newText = '';
  for (let i = 0; i < str.length; i++) {
    let char = str[i];
    newText = char + newText; /* put char in the beginning to newText */
  }
  return newText;
}
console.log(stringReverser(question));
// ?tpircsavaj ni gnirts a esrever ot woH

Using string method:

let question = 'How to reverse a string in javascript?';
function reverseString(str) {
  return str.split('').reverse().join('');
}
console.log(reverseString(question));
// ?tpircsavaj ni gnirts a esrever ot woH

6. CHECK WHETHER A YEAR IS A LEAP YEAR OR NOT

There are multiple ways we can find a year is a leap year or not. But first we need to understand the logic, when we call a year as leap. There are few conditions you will need to check if you want to identify leap year. These conditions are:

To determine whether a year is a leap year, follow these steps:

  • Step 1. Divide a year by 400, if it’s divisible then it’s a leap year. If not divisible follow step 2.
  • Step 2. Divide a year by 100, if it’s divisible then it’s not a leap year. If divisible follow step 3.
  • Step 3. Divide a year by 4, if it’s divisible then it’s a leap year.

We can implement these above condition in various way:

// Way: 1
function leapYearChecker(year) {
  if (year % 400 === 0) return true;
  if (year % 100 === 0) return false;
  return year % 4 === 0;
}

console.log(leapYearChecker(1800)); // false
console.log(leapYearChecker(2012)); // true
console.log(leapYearChecker(2020)); // true
console.log(leapYearChecker(1900)); // false

// Way: 2
function leapYearChecker(year) {
  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
    return 'The year is a leap Year';
  } else {
    return 'The Year is not a leap year';
  }
}

console.log(leapYearChecker(1800)); // The Year is not a leap year
console.log(leapYearChecker(2012)); // The year is a leap Year
console.log(leapYearChecker(2020)); // The year is a leap Year
console.log(leapYearChecker(1900)); // The Year is not a leap year

// Way 3:
function leapYearChecker(year) {
  return year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;
}

console.log(leapYearChecker(1700)); // false
console.log(leapYearChecker(2012)); // true
console.log(leapYearChecker(2020)); // true
console.log(leapYearChecker(1900)); // false

7. CALCULATE FACTORIAL OF A NUMBER USING FOR LOOP

Before calculating factorial first we need to understand how factorial calculation works. In mathematics we use exclamation to denote factorial like 5! (five factorial). What that means is nothing but the product of positive integer from 1 to n (1 to 5 in this case) like (54321). So 5! is equivalent to 120. We can implement factorial calculation in multiple ways. I will share how we can use for loop to calculate factorial then will share how we can create a function for calculating factorial.

/* assume initial value such that it will not affect the result,
 e.g. for multiply assume initial value 1 */

// Iterative method, for loop:
let factorialValue = 1;
// for now calculate the factorial of 5, later we will create a reusable function
for (let i = 1; i <= 5; i++) {
  factorialValue = factorialValue * i;
}
console.log(factorialValue); // 120

// Create a function:
function getFactorial(n) {
  let factorialValue = 1;
  for (let i = 1; i <= n; i++) {
    factorialValue = factorialValue * i;
  }
  return factorialValue;
}

console.log(getFactorial(5)); // 120

8. CALCULATE FACTORIAL OF A NUMBER USING A WHILE LOOP

In the above problem solving exercise we used for loop, similarly we can use while loop for factorial calculation in following way:

// using while loop:
let i = 1;
let factorialValue = 1;
// for now calculate the factorial of 5, later we will create a reusable function
while (i <= 5) {
  factorialValue = factorialValue * i;
  i++;
}
console.log(factorialValue); // 120

// Create a function:
function getFactorial(n) {
  let i = 1;
  let factorialValue = 1;
  while (i <= n) {
    factorialValue = factorialValue * i;
    i++;
  }
  return factorialValue;
}

console.log(getFactorial(6)); // 720

9. CALCULATE FACTORIAL IN A RECURSIVE FUNCTION

Another way to find the factorial is using recursive function. What is recursive function anyways? Recursive means repetition, when a function call itself and repeat the process until certain condition is met, then it’s called recursive function. To find the factorial in recursive way, first we need to understand what other alternative way we can write factorial, in a way that we can repeat the process until a certain condition met. Since 5! is equivalent to 4!*5, which is equivalent to (5-1)!*5, for a whole number n we can write (n-1)!*n. We will use similar technique in recursive function so that we can repeat the process.

5!=1*2*3*4*5
0! = 1
2! = 1*2
3! = 1*2*3
4! = 1*2*3*4
5! = 1*2*3*4*5 = 4!*5 = (5-1)! * 5
n! = (n-1)! * n

In the following function when function calls itself and after each iteration the number n will change and when n get to 0 the function will stop iteration.

function getFactorial(n) {
  if (n == 0) {
    return 1;
  } else {
    return getFactorial(n - 1) * n;
  }
}

console.log(getFactorial(5)); // 120

10. CREATE A FIBONACCI SERIES USING A FOR LOOP

A fibonacci sequence is a series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21

To create fibonacci series first we need to understand how each number in fibonacci sequence calculated. In fibonacci sequence any next number is calculated by adding two number before it. For example, in the above sequence the third number is calculated (0+1) or 1, fourth number is calculated (1+1) or 2 and so on. We need to implement the same logic in such a way that we can add two numbers for next number. In simple way we can write:

Position 2, 3, 4, 5, n ,i respectively:
fiboSeries[2] = fiboSeries[2 - 1] + fiboSeries[2 - 2];
fiboSeries[3] = fiboSeries[3 - 1] + fiboSeries[3 - 2];
fiboSeries[4] = fiboSeries[4 - 1] + fiboSeries[4 - 2];
fiboSeries[5] = fiboSeries[5 - 1] + fiboSeries[5 - 2];
fiboSeries[n] = fiboSeries[n - 1] + fiboSeries[n - 2];
fiboSeries[i] = fiboSeries[i - 1] + fiboSeries[i - 2];

Now we can apply for loop to create fibonacci series:

let fiboSeries = [0, 1];

for (let i = 2; i <= 12; i++) {
  fiboSeries[i] = fiboSeries[i - 1] + fiboSeries[i - 2];
}

console.log(fiboSeries);
// [ 0,  1,  1,  2,  3,  5, 8, 13, 21, 34, 55, 89, 144 ]

// Create a function:
function getFibonacciSeries(n) {
  let fiboSeries = [0, 1];

  for (let i = 2; i <= n; i++) {
    fiboSeries[i] = fiboSeries[i - 1] + fiboSeries[i - 2];
  }
  return fiboSeries;
}

console.log(getFibonacciSeries(12));
// [ 0,  1,  1,  2,  3,  5, 8, 13, 21, 34, 55, 89, 144 ]

11. FIBONACCI ELEMENT IN A RECURSIVE WAY

We already learned about recursive function. To find a fibonacci element we need to create and repeat the similar formula we used in the previous example using recursive function. Since in fibonacci sequence any next number is calculated by adding two number before it, and the sequence start with 0 , 1, we can create the following function to get a fibonacci element.

function getFibonacci(n) {
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  } else {
    return getFibonacci(n - 1) + getFibonacci(n - 2);
  }
}

console.log(getFibonacci(10)); // 55

12. CREATE FIBONACCI SERIES IN A RECURSIVE WAY

Before I showed you how to use for loop to create fibonacci series, in this problem solving exercise I will use recursive function to create fibonacci series. In this recursive function we will repeat the addition process until n equal 0 or n equal 1, and push each element in each iteration.

function getFibonacciSeries(n) {
  if (n == 0) {
    return [0];
  } else if (n == 1) {
    return [0, 1];
  } else {
    // find array with nth item
    let fiboSeries = getFibonacciSeries(n - 1);
    let nextElement = fiboSeries[n - 1] + fiboSeries[n - 2];
    fiboSeries.push(nextElement);
    return fiboSeries;
  }
}

console.log(getFibonacciSeries(1)); // [ 0, 1 ]
console.log(getFibonacciSeries(2)); // [ 0, 1, 1 ]
console.log(getFibonacciSeries(3)); // [ 0, 1, 1, 2 ]
console.log(getFibonacciSeries(4)); // [ 0, 1, 1, 2, 3 ]
console.log(getFibonacciSeries(10)); // [ 0, 1,  1,  2,  3, 5, 8, 13, 21, 34, 55]

13. CHECK WHETHER A NUMBER IS A PRIME NUMBER OR NOT

When an integer number is not a product of two other integer number we call that number as prime number. We can verify a number is prime or not in this following way:

function isPrime(num) {
  for (i = 2; i < num; i++) {
    if (num % i == 0) {
      return `${num} is not a Prime Number`;
    }
  }
  return `${num} is a Prime number`;
}

console.log(isPrime(128)); // 128 is not a Prime Number
console.log(isPrime(79)); // 79 is a Prime number

Leave a Comment