Factorial of a number

Dec 24, 2023

Steps:

  • Create program using recursion
  • Until the value is not equal to zero, the recursive function will call itself
function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

factorial(5)

References:

Categories : JavaScript   Interview   Coding

Find if string is a palindrome?

Dec 23, 2023

Steps:

  • Loop through the characters in the string
  • Check if the first letter match the last letter
  • Check second letter match the second to last letter
function palindrome(str) {
    for(let i = 0; str.length - i > i; i++) {
        if (str[i] !== str[str.length - 1 - i]) {
            return false;
        }
    }
    return true;
}

palindrome('madam')

References:

Categories : JavaScript   Interview   Coding

Find missing number in an array?

Dec 21, 2023

Steps:

  • Create a set object having values within the range of initial and final values of the provided array
  • Then compare it with the provided array to retrieve the missing value
function findMissingNumberInArray(arr) {
    const mySet = new Set();
    const firstEl = arr[0];
    const lastEl = arr[arr.length - 1];
    for(let i = firstEl; i <= lastEl; i++) {
        mySet.add(i);
    }
    for(let x = 0; x < arr.length; x++) {
        if(mySet.has(arr[x])) {
            mySet.delete(arr[x]);
        }
    }
    return Array.from(mySet);
}

findMissingNumberInArray([1,4,6,7,8,9]);

References:

Categories : JavaScript   Interview   Coding

Find largest and smallest number in an array?

Dec 19, 2023

Steps:

  • Assign first element of array to largest and smallest
  • Iterate over the array
  • If element is larger than largest, assign to largest
  • If element is smaller than smallest, assign to smallest
function findLargestSmallestInArray(arr) {
    let largest = arr[0];
    let smallest = arr[0];

    for(let i = 0; i< arr.length; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
        if (arr[i] < smallest) {
            smallest = arr[i];
        }
    }

    return [largest, smallest];
}

findLargestSmallestInArray([20,14,592,57,2,4,50,1]);

References:

Categories : JavaScript   Interview   Coding

How Do You Reverse a String?

Dec 17, 2023

Steps:

  • Create a empty string newString
  • Create a for loop, the starting point of the loop with be str.length - 1 which will be the last character of the string
  • Continue for loop till i is greater than or equals 0, decrement i after each iteration
function reverseString(str) {
    let newString = "";

   for(let i = str.length - 1 ; i >= 0; i--) {
       newString = newString + str[i];
   }

    return newString;
}

reverseString('hello');

References:

Categories : JavaScript   Interview   Coding