DEV Community

Saqib Jamil
Saqib Jamil

Posted on • Edited on

5 Javascript coding interview questions - Part 2

Javascript coding interview questions part 1
Javascript coding interview questions part 3

1: Two Sum - Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target.

function twoSum(nums, target) {
  const numMap = new Map();

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (numMap.has(complement)) {
      return [numMap.get(complement), i];
    }
    numMap.set(nums[i], i);
  }

  return null; // If no such pair exists
}

// Test
console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]
Enter fullscreen mode Exit fullscreen mode

2: Find the Largest Number in an Array:
Write a function that takes an array of numbers as input and returns the largest number.

function findLargestNumber(arr) {
  return Math.max(...arr);
}

// Test
console.log(findLargestNumber([3, 5, 1, 9, 2])); // Output: 9

Enter fullscreen mode Exit fullscreen mode

3: Find the Longest Word
Write a function that takes a sentence as input and returns the longest word in the sentence.

function findLongestWord(sentence) {
  const words = sentence.split(' ');
  let longestWord = '';

  for (const word of words) {
    if (word.length > longestWord.length) {
      longestWord = word;
    }
  }

  return longestWord;
}

// Test
console.log(findLongestWord('The quick brown fox jumped over the lazy dog')); // Output: "jumped"

Enter fullscreen mode Exit fullscreen mode

4: Count Vowels
Write a function that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string.

function countVowels(str) {
  const vowels = str.match(/[aeiou]/gi);
  return vowels ? vowels.length : 0;
}

// Test
console.log(countVowels('Hello World')); // Output: 3

Enter fullscreen mode Exit fullscreen mode

5: Find Missing Number
Write a function that takes an array containing integers from 1 to n (excluding one number) and returns the missing number.

function findMissingNumber(nums) {
  const n = nums.length + 1;
  const totalSum = (n * (n + 1)) / 2;
  const currentSum = nums.reduce((sum, num) => sum + num, 0);
  return totalSum - currentSum;
}

// Test
console.log(findMissingNumber([1, 2, 4, 5])); // Output: 3

Enter fullscreen mode Exit fullscreen mode

Javascript coding interview questions part 1
Javascript coding interview questions part 3

Top comments (0)