javascript-algorithm

The Ultimate Guide to JavaScript Interview Algorithms and Solutions

1. Find a duplicate number in an array of integers in JavaScript.

2. Find the missing number in a given integer Array in JavaScript.

3. Find the largest and smallest number in an unsorted array of integers in JavaScript.

4. Return an array showing the cumulative sum at each index of an array of integers in JavaScript.

5. Find all duplicate numbers in an array with multiple duplicates in JavaScript.

6. Remove all duplicates from an array of integers in JavaScript.

7. Find all pairs in an array of integers whose sum is equal to a given number in JavaScript.

8. Replace One Character With Another in JavaScript.

9. Reverse String in JavaScript.

10. Remove all even integers from an array in JavaScript.

11. Check and Verify a word as palindrome in JavaScript.

12. How to find the factorial of a Number in JavaScript?

13. Find the all duplicate characters or number with index(count) from the input string in javascript.

14. How to check prime number in JavaScript?

15. How to check Prime Factors in JavaScript?

16. How do get nth Fibonacci number?

17. How do Swap number without temp?

1. Find a duplicate number in an array of integers

Solutions-1

const arr = [1,2,3,4,5,6,7,7,8,6,10];
const findDupes = (arr) => {
  const observed = {};
  for(let i = 0; i < arr.length; i++) {
    if(observed[arr[i]]) {
      return arr[i]
    } else {
      observed[arr[i]] = arr[i];
    }
  }
  
  return false;
}
console.log(findDupes(arr)); // Returns 7

Solution- 2

const array = [1, 2, 3, 4, 5, 3, 4, 52, 356, 3, 4, 5, 6];

const duplicates = array.filter((value, index) => {
  return array.indexOf(value) !== index && array.lastIndexOf(value) === index;
});

console.log("Duplicate numbers:", duplicates); // Output: Duplicate numbers: [3, 4, 5]

Solution-3

2. Find the missing number in a given integer Array.

let arr = [1,2,3,4,5,6,7,8,10];
const findMissingNum = (arr) => {
  for(var i = 0; i < arr.length - 1; i++) {
    if(arr[i] + 1 != arr[i+1] ) {
      return arr[i] + 1;
    }
  }
  
  return false;
}
console.log(findMissingNum(arr)); // Returns 9, the missing number

3. Find the largest and smallest number in an unsorted array of integers.

const arr = [1, 2, 3, 4, 100];
const findMaxMin = (arr) => {
  let max = arr[0];
  let min = arr[0];
  
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] > max) {
      max = arr[i];
    } else if (arr[i] < min) {
      min = arr[i];
    }
  }
  
  return {
    "max": max,
    "min": min
  };
}
console.log(findMaxMin(arr)); // Returns object { "max": 100, "min": 1 }

4. Return an array showing the cumulative sum at each index of an array of integers.

let arr = [1,3,5,7];
const cumulativeSum = list => {
  let result = [list[0]];
  
  for(let i = 1; i < list.length; i++) {
    result.push(list[i] + result[i-1]);
  } 
  
  return result;
}
console.log(cumulativeSum(arr)); // Returns [1, 4, 9, 16]

5. Find all duplicate numbers in an array with multiple duplicates

const arr = [1,1,2,3,4,5,6,7,8,6,6,7,7,7,10,10];
const returnMultipleDupesArray = (arr) => {
  let observed = {};
  let dupesArray = [];
  
  for(let i = 0; i < arr.length; i++) {
 
    if(observed[arr[i]]) {
      if(observed[arr[i]] === 1) {
        dupesArray.push(arr[i]);
      }
      
      observed[arr[i]] = observed[arr[i]] + 1;
    } else {
      observed[arr[i]] = 1;
    }
  }
  
  return dupesArray;
}
console.log(returnMultipleDupesArray(arr)); // prints [1, 6, 7, 10]

6. Remove all duplicates from an array of integers.

Solution-1

const arr = [1, 1, 1, 1, 1, 1, 1];const removeDupes = (arr) => {
  let result = [];
  let previous = arr[0];
  result[0] = previous;
  
  for(let i = 0; i < arr.length; i++) {
    
    if (arr[i] != previous) {
      result.push(arr[i]);
    }
    
    previous = arr[i];
  }
  
  return result;
}
console.log(removeDupes(arr)); // Output  prints [1]

Solution-2

const arr = [1, 2, 3, 4, 5, 6, 7, 7, 8, 6, 10];

const uniqueValues = [...new Set(arr)];

console.log(uniqueValues); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 10]

7. Find all pairs in an array of integers whose sum is equal to a given number.

let arr = [1,5,6,1,0,1];
const findSumPairs = (arr, value) => {
  let sumsLookup = {};
  let output = [];
  
  for(let i = 0; i < arr.length; i++) {
    let targetVal = value - arr[i];
    
    if(sumsLookup[targetVal]) {
      output.push([arr[i], targetVal]);
    }  
    
    sumsLookup[arr[i]] = true;
  }
  
  return output;
}
console.log(findSumPairs(arr, 6));

// Output [ [ 5, 1 ], [ 1, 5 ], [ 0, 6 ], [ 1, 5 ] ]

8. Replace One Character With Another.

function replaceChar(inputStr, replaceThis, withThis) {
    var retval = [];

    for (var i = 0; i < inputStr.length; i++) {
        if (inputStr[i] === replaceThis) {
            retval.push(withThis);
        } else {
            retval.push(inputStr[i]);
        }
    }

    return retval.join('');
}

console.log(replaceChar('hello world', 'l', 'X')); //Output heXXo worXd

9. How to Reverse a String?

Solution – 1

function reverseString(inputStr) {
    var retval = [];
    var tokens = inputStr.split('');

    for (var i = tokens.length - 1; i >= 0; i--) {
        retval.push(inputStr[i]);
    }

    return retval.join('');
}

console.log(reverseString('Hello World')); // Output dlroW olleH

Solution – 2

function reverseString(str) {
    return str.split("").reverse().join("");
}
console.log(reverseString("hello")); // output: olleh

Solution – 3 ES6

let string = "Hello"
string = [...string].reverse().join("");

console.log(string); // output : olleh

Solution – 4 ES6

function reverseWords(input) {
    // Split the input string into words, reverse each word, and join them back into a string
    return input.split(' ').map(word => word.split('').reverse().join('')).join(' ');
}

var input = "sushil kumar";
var output = reverseWords(input);
console.log(output); // Output: "lihsus ramuk"

10. Remove all even integers from an array.

Solution – 1

const inputData = [4, 1, 9, 10, 15, 22, 5, 14]
removeEvenNumbers (inputData) => {
    let odds = []
    for (let number of inputData) {
        if (number % 2 != 0) odds.push(number)
    }
  return odds
}
console.log(removeEvenNumbers(inputData)))
// Output [4, 10, 22, 14]

Solution – 2

removeEvenNumbers(inputData) => {
    return inputData.filter((number => (number % 2) != 0))
}
console.log(removeEvenNumbers(inputData))

11. Check and Verify a word as Palindrome.

Solution – 1

function isPalindrome(str){
    var i, len = str.length;
    for(i =0; i<len/2; i++){
      if (str[i]!== str[len -1 -i]) // str[0] !== str[3] i.e., r !== r
         return false;
    }
    return true;
  }
  
  console.log(isPalindrome('radar')); // Output return true

Solution – 2

function isPalindrome(s) {
    // Reverse the string
    let reversed = s.split('').reverse().join('');
    // Check if the reversed string is equal to the original (case-sensitive)
    return s === reversed;
}

let strings = ['ab', 'ba', 'bv'];

strings.forEach(string => {
    if (isPalindrome(string)) {
        console.log(`${string} is a palindrome.`);
    } else {
        console.log(`${string} is not a palindrome.`);
    }
});

12. How to find the factorial of a Number.

Solution-1

 function factorialNumber(n){
    let answer = 1;
    if (n == 0 || n == 1){
      return answer;
    }else{
      for(var i = n; i >= 1; i--){
        answer = answer * i;
      }
      return answer;
    }  
  }
  let n = 5;
  answer = factorialNumber(n)
  console.log("The factorial  Number of " + n + " is " + answer);
// output is 120.

Solution-2

// Function to calculate factorial
const factorial = n => {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
};

// Higher-order function to check if a number is a factorial number
const isFactorialNumber = num => {
    // Generate factorials until they exceed num
    const factorials = Array.from({ length: num }, (_, i) => factorial(i));
    
    // Check if num exists in the generated factorials array
    return factorials.includes(num);
};

// Example usage:
console.log(isFactorialNumber(24)); // true, since 24 = 4!
console.log(isFactorialNumber(25)); // false

13. Find the all duplicate characters or number with index(count) from the input string.

function findDuplicatesCharWithNumber(str)
{
    var count = {};
    for (var i = 0; i < str.length; i++) {
        count[str[i]] = 0;
        
    }
     
    for (var i = 0; i < str.length; i++) {
        count[str[i]]++;
    }
 
    for (var ele in count) {
        if (count[ele] > 1)
            console.log(`${ele}=${count[ele]}`);
    }
}

// for number
var str = "23232232093239230923";
findDuplicatesCharWithNumber(str);    // output is 0=2, 2=8, 3=7, 9=3
// for string
var str = "abscdertnsjmmajmansanasnanma";
findDuplicatesCharWithNumber(str);  // output is a=7, s=4, n=5, j=2, m=4

14. How to check prime number in JavaScript?

Solution – 1

function isPrime(n)
{

  if (n===1)
  {
    return false;
  }
  else if(n === 2)
  {
    return true;
  }
  else
  {
    for(var x = 2; x < n; x++)
    {
      if(n % x === 0)
      {
        return false;
      }
    }
    return true;  
  }
}
console.log(isPrime(13));  // Output: true

Solution – 2


function isPrime(n){
  var divisor = 2;

  while (n > divisor){
    if(n % divisor == 0){
     return false; 
    }
    else
      divisor++;
  }
  return true;
}

console.log(isPrime(13));
 // Output= true

15. How to check Prime Factors in JavaScript?

function primeFactors(n){
   var factors = [], 
       divisor = 2;
   
   while(n>2){
     if(n % divisor == 0){
        factors.push(divisor); 
        n= n/ divisor;
     }
     else{
       divisor++;
     }     
   }
   return factors;
 }
 
console.log(primeFactors(105));  // Output: [ 3, 5, 7 ]

16. How do get nth Fibonacci series number?

Solution – 1 for Fibonacci series


function fibonacciSeries(n){
  var fibonac = [0, 1];
  
  if (n <= 2) return 1;

  for (var i = 2; i <=n; i++ ){
    fibonac[i] = fibonac[i-1]+fibonac[i-2];
    console.log(fibonac[i]); // Print here Fibonacci series: 1
 2 3 5 8 13 21 34 55
  }

 return fibonac[n];
} 

console.log(fibonacciSeries(10));  // Output is 55

17. How to swap two numbers without using a temporary variable?

Solution – 1

function swapNumb(a, b){
  console.log('Before swap Output: ','a: ', a, 'b: ', b);
// Before swap Output:  a:  2 b:  3
  b = b -a;
  a = a+ b;
  b = a-b;
  console.log('After swap Output: ','a: ', a, 'b: ', b);  
// After swap Output:  a:  3 b:  2
}

swapNumb(2, 3);

Solution – 2

function swapNumb(a, b){
  console.log('Before swap Output: ','a: ', a, 'b: ', b);

  // Before swap Output:  a:  2 b:  3
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
  console.log('After swap Output: ','a: ', a, 'b: ', b); 
 // After swap Output:  a:  3 b:  2
}
swapNumb(2, 3);
JavaScript Algorithm.

Find a Duplicate Number in an Array

To identify a duplicate number in an array, you can track the numbers you encounter using a data structure like a set. As you iterate through the array, check if each number is already in the set. If it is, that’s a duplicate; otherwise, add the number to the set.

Find the Missing Number in a Given Integer Array

If you have an array containing numbers from 1 to n with one number missing, you can calculate the expected sum of all numbers from 1 to n using the sum formula for an arithmetic series. Then subtract the sum of the numbers present in the array from this expected sum to find the missing number.

Find the Largest and Smallest Number in an Unsorted Array

To find the largest and smallest numbers, iterate through the array and compare each number to the current known largest and smallest values. Update these values as needed during the iteration.

Return an Array Showing the Cumulative Sum at Each Index

Create a new array where each element at index i represents the sum of all elements in the original array up to index i. You can achieve this by keeping a running total of the sum as you iterate through the original array.

Find All Duplicate Numbers in an Array with Multiple Duplicates

Use a frequency counter to track how many times each number appears in the array. After counting, collect all numbers that appear more than once into a list of duplicates.

Remove All Duplicates from an Array of Integers

Use a set to automatically handle uniqueness. By adding each number to the set, duplicates are inherently removed because sets do not allow duplicate entries. Convert the set back to an array to get the result.

Find All Pairs in an Array Whose Sum Equals a Given Number

Use a set to keep track of the numbers you have seen so far. For each number in the array, calculate its complement (the number needed to reach the target sum) and check if this complement is already in the set. If it is, you’ve found a pair

Replace One Character with Another

To replace characters, iterate through the string and replace occurrences of a specific character with another character. This can be efficiently done using string manipulation functions available in many programming languages.

Reverse a String

To reverse a string, you can convert the string into an array of characters, reverse the order of the characters, and then join the characters back into a string.

Remove All Even Integers from an Array

Filter out even numbers from the array by checking each number and retaining only those that are odd

Check and Verify a Word as a Palindrome

A palindrome reads the same forwards and backwards. To check if a word is a palindrome, compare the string to its reverse. Ignore case and non-alphanumeric characters for a more robust solution

Find the Factorial of a Number

The factorial of a number is the product of all positive integers up to that number. It can be computed iteratively by multiplying the numbers from 1 to n