Interview Questions

1) Write a function that takes a string as input and returns the string reversed.


function reverseString(str) {
  return str.split('').reverse().join('');
}

// Example usage:
console.log(reverseString('hello'));  // Output: 'olleh'

Explanation:

  1. split('') breaks the string into an array of characters.
  2. reverse() reverses the array.
  3. join('') joins the array back into a string.

2) Write a function that returns the largest number in an array.


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

// Example usage:
console.log(findLargest([3, 5, 7, 2, 8]));  // Output: 8

Explanation:

  • Math.max(...arr) spreads the array elements as individual arguments to the Math.max function, which returns the largest number.

3) Check if a String is a Palindrome


function isPalindrome(str) {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
}

// Example usage:
console.log(isPalindrome('madam'));  // Output: true
console.log(isPalindrome('hello'));  // Output: false

Explanation:

  • The string is reversed and compared with the original string. If they are the same, it's a palindrome.

4) Find the Missing Number in an Array (1 to N)


function findMissingNumber(arr, n) {
  const total = (n * (n + 1)) / 2;  // Sum of numbers from 1 to N
  const sum = arr.reduce((acc, num) => acc + num, 0);
  return total - sum;
}

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

Explanation:

  • The sum of the numbers from 1 to N is calculated using the formula (n * (n + 1)) / 2.
  • The sum of the array elements is subtracted from this total to find the missing number.

5) Find the First Non-Repeating Character


function firstNonRepeatingCharacter(str) {
  const frequency = {};

  for (let i = 0; i < str.length; i++) {
    frequency[str[i]] = (frequency[str[i]] || 0) + 1;
  }

  for (let i = 0; i < str.length; i++) {
    if (frequency[str[i]] === 1) {
      return str[i];
    }
  }

  return null;
}

// Example usage:
console.log(firstNonRepeatingCharacter('swiss'));  // Output: 'w'
console.log(firstNonRepeatingCharacter('aabbcc'));  // Output: null

Explanation:

  • A frequency map is created to count the occurrences of each character in the string.
  • The string is then iterated again to find the first character with a frequency of 1.

6) Merge Two Sorted Arrays


function mergeSortedArrays(arr1, arr2) {
  let i = 0;
  let j = 0;
  let mergedArray = [];

  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] < arr2[j]) {
      mergedArray.push(arr1[i]);
      i++;
    } else {
      mergedArray.push(arr2[j]);
      j++;
    }
  }

  return mergedArray.concat(arr1.slice(i), arr2.slice(j));
}

// Example usage:
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6]));  // Output: [1, 2, 3, 4, 5, 6]

Explanation:

  • Two pointers, i and j, are used to traverse the two arrays.
  • The smaller element between arr1[i] and arr2[j] is pushed to the mergedArray until one of the arrays is exhausted.
  • The remaining elements of both arrays are then concatenated to the merged result.

7) Implement a Debounce Function


function debounce(func, delay) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func(...args);
    }, delay);
  };
}

// Example usage:
const debouncedFunction = debounce(() => console.log('Debounced!'), 1000);
debouncedFunction();  // The message will be logged after 1 second.

Explanation:

  • The debounce function ensures that the provided function is only invoked after the given delay has passed since the last invocation.

8) Flatten a Nested Array


function flattenArray(arr) {
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc.push(...flattenArray(item));  // Recursively flatten nested arrays
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
}

// Example usage:
console.log(flattenArray([1, [2, 3], [4, [5, 6]], 7]));  // Output: [1, 2, 3, 4, 5, 6, 7]

Explanation:

  • The reduce function is used to iterate over the array.
  • If an element is an array, it's recursively flattened; otherwise, the element is added to the result array.

9) Remove Duplicates from an Array


function removeDuplicates(arr) {
  return [...new Set(arr)];
}

// Example usage:
console.log(removeDuplicates([1, 2, 3, 1, 2, 4]));  // Output: [1, 2, 3, 4]

Explanation:

  • Using a Set will automatically eliminate duplicates since sets only store unique values. Then, we use the spread operator (...) to convert the Set back into an array.

10) Find the Second Largest Number in an Array


function secondLargest(arr) {
  let first = -Infinity;
  let second = -Infinity;
  
  for (let num of arr) {
    if (num > first) {
      second = first;
      first = num;
    } else if (num > second && num !== first) {
      second = num;
    }
  }
  
  return second === -Infinity ? null : second;
}

// Example usage:
console.log(secondLargest([3, 5, 7, 2, 8]));  // Output: 7
console.log(secondLargest([3, 3, 3]));  // Output: null

Explanation:

  • We iterate through the array, keeping track of the two largest numbers. If we encounter a number larger than the current largest, it becomes the largest, and the previous largest becomes the second largest.

11) Sum of All Numbers in a Range


function sumInRange(start, end) {
  let sum = 0;
  for (let i = start; i <= end; i++) {
    sum += i;
  }
  return sum;
}

// Example usage:
console.log(sumInRange(1, 5));  // Output: 15 (1 + 2 + 3 + 4 + 5)

Explanation:

  • We use a simple for loop to iterate from start to end and accumulate the sum of numbers in that range.

12) Count Occurrences of a Value in an Array


function countOccurrences(arr, value) {
  return arr.filter(item => item === value).length;
}

// Example usage:
console.log(countOccurrences([1, 2, 2, 3, 2], 2));  // Output: 3

Explanation:

  • We use the filter() method to create an array of elements that match the specified value, and then return the length of that array, which gives us the count of occurrences.

13) Find the Intersection of Two Arrays


function intersection(arr1, arr2) {
  return arr1.filter(item => arr2.includes(item));
}

// Example usage:
console.log(intersection([1, 2, 3], [3, 4, 5]));  // Output: [3]

Explanation:

  • The filter() method is used on the first array to keep only the elements that are also found in the second array using the includes() method.

14) Check if a Number is Prime


function isPrime(num) {
  if (num <= 1) return false;
  
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  
  return true;
}

// Example usage:
console.log(isPrime(7));  // Output: true
console.log(isPrime(10));  // Output: false

Explanation:

  • A prime number is only divisible by 1 and itself. We loop from 2 to the square root of num to check for any divisors. If any number divides num, it's not prime.

15) Find the Missing Character in a String


function findMissingCharacter(str1, str2) {
  const sortedStr1 = str1.split('').sort().join('');
  const sortedStr2 = str2.split('').sort().join('');
  
  for (let i = 0; i < sortedStr1.length; i++) {
    if (sortedStr1[i] !== sortedStr2[i]) {
      return sortedStr1[i];
    }
  }
  
  return sortedStr1[sortedStr1.length - 1];  // If the missing character is the last one
}

// Example usage:
console.log(findMissingCharacter('abcd', 'abc'));  // Output: 'd'

Explanation:

  • By sorting both strings, we can easily compare them character by character. The first discrepancy will reveal the missing character.

16) Implement a Throttle Function


function throttle(func, delay) {
  let lastCall = 0;

  return function(...args) {
    const now = new Date().getTime();
    if (now - lastCall >= delay) {
      func(...args);
      lastCall = now;
    }
  };
}

// Example usage:
const throttledFunc = throttle(() => console.log('Throttled!'), 1000);
throttledFunc();  // Will log 'Throttled!' immediately
throttledFunc();  // Will be ignored if less than 1 second passed

Explanation:

  • The throttle function ensures that the wrapped function is only executed once within the specified time interval (delay). If it's called multiple times within that interval, only the first call is executed.