JS: Interview Algorithm Question Answers

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]

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.

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]

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.

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

12. How to find the factorial of a Number.

 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.

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

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);