JavaScript Programs for Interview

Some JavaScript interview programs and their solutions:

1. Reverse a String:

Question: Write a function to reverse a string.

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

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

2. Check for Palindrome:

Question: Write a function to check if a string is a palindrome (reads the same forwards and backwards).

function isPalindrome(str) {
  str = str.toLowerCase().replace(/[^a-zA-Z0-9]/g, ''); // Remove non-alphanumeric characters and convert to lowercase
  return str === str.split('').reverse().join('');
}

console.log(isPalindrome('racecar')); // Output: true

3. Find the Factorial:

Question: Write a function to find the factorial of a number.

function factorial(num) {
  if (num === 0 || num === 1) {
    return 1;
  }
  return num * factorial(num - 1);
}

console.log(factorial(5)); // Output: 120

4. Remove Duplicates from an Array:

Question: Write a function to remove duplicate elements from an array.

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

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

5. Find the Missing Number:

Question: Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the missing number.

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

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

6. Find the Largest Sum of Contiguous Subarray (Kadane’s Algorithm):

Question: Write a function to find the largest sum of a contiguous subarray within an array.

function maxSubarraySum(nums) {
  let maxSum = nums[0];
  let currentSum = nums[0];

  for (let i = 1; i < nums.length; i++) {
    currentSum = Math.max(nums[i], currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
  }

  return maxSum;
}

console.log(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // Output: 6

Certainly! Here are some more JavaScript interview questions and their solutions:

7. Find the First Non-Repeating Character:

Question: Write a function to find the first non-repeating character in a string.

function firstNonRepeatingChar(str) {
  const charCount = {};

  for (const char of str) {
    charCount[char] = (charCount[char] || 0) + 1;
  }

  for (const char of str) {
    if (charCount[char] === 1) {
      return char;
    }
  }

  return null;
}

console.log(firstNonRepeatingChar('leetcode')); // Output: 'l'

8. Check for Anagrams:

Question: Write a function to check if two strings are anagrams of each other.

function areAnagrams(str1, str2) {
  return str1.split('').sort().join('') === str2.split('').sort().join('');
}

console.log(areAnagrams('listen', 'silent')); // Output: true

9. Find the Longest Common Prefix:

Question: Write a function to find the longest common prefix among an array of strings.

function longestCommonPrefix(strs) {
  if (strs.length === 0) return '';

  let prefix = strs[0];

  for (let i = 1; i < strs.length; i++) {
    while (strs[i].indexOf(prefix) !== 0) {
      prefix = prefix.substring(0, prefix.length - 1);
    }
  }

  return prefix;
}

console.log(longestCommonPrefix(['flower', 'flow', 'flight'])); // Output: 'fl'

10. Validate Parentheses:

Question: Write a function to determine if a given string containing parentheses is valid (all opening brackets are closed in the correct order).

function isValidParentheses(s) {
  const stack = [];
  const brackets = { '(': ')', '[': ']', '{': '}' };

  for (const char of s) {
    if (brackets[char]) {
      stack.push(char);
    } else {
      const top = stack.pop();
      if (brackets[top] !== char) return false;
    }
  }

  return stack.length === 0;
}

console.log(isValidParentheses('()[]{}')); // Output: true

11. Implement a Queue Using Stacks:

Question: Implement a queue data structure using two stacks.

class MyQueue {
  constructor() {
    this.stack1 = [];
    this.stack2 = [];
  }

  push(x) {
    this.stack1.push(x);
  }

  pop() {
    if (this.stack2.length === 0) {
      while (this.stack1.length > 0) {
        this.stack2.push(this.stack1.pop());
      }
    }
    return this.stack2.pop();
  }

  peek() {
    if (this.stack2.length === 0) {
      while (this.stack1.length > 0) {
        this.stack2.push(this.stack1.pop());
      }
    }
    return this.stack2[this.stack2.length - 1];
  }

  empty() {
    return this.stack1.length === 0 && this.stack2.length === 0;
  }
}