Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
what is promise

Frequently Asked Questions

By Saket Bhatnagar•June 14, 2025•Beginner to Intermediate

Table of Contents

  1. frequently asked questions

frequently asked questions

  1. 1Reverse a String
    1function reverseString(str) {
    2 // Method 1: Using array methods
    3 return str.split('').reverse().join('');
    4
    5 // Method 2: Using loop
    6 // let reversed = '';
    7 // for(let i = str.length - 1; i >= 0; i--) {
    8 // reversed += str[i];
    9 // }
    10 // return reversed;
    11}
    12reverseString("Chombi"); // Output: "ibmoCh"
    13
  2. 2Find the Factorial of a Number
    1function factorial(n) {
    2 // Method 1: Using recursion
    3 if (n === 0 || n === 1) return 1;
    4 return n * factorial(n - 1);
    5
    6 // Method 2: Using loop
    7 // let result = 1;
    8 // for(let i = 2; i <= n; i++) {
    9 // result *= i;
    10 // }
    11 // return result;
    12}
    13factorial(5); // Output: 120
    14
  3. 3Check if String is Palindrome
    1function isPalindrome(str) {
    2 // Remove non-alphanumeric characters and convert to lowercase
    3 str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
    4
    5 // Method 1: Using array methods
    6 return str === str.split('').reverse().join('');
    7
    8 // Method 2: Using two pointers
    9 // let left = 0;
    10 // let right = str.length - 1;
    11 // while(left < right) {
    12 // if(str[left] !== str[right]) return false;
    13 // left++;
    14 // right--;
    15 // }
    16 // return true;
    17}
    18isPalindrome("A man, a plan, a canal: Panama"); // Output: true
    19
  4. 4Find the Fibonacci Sequence
    1function fibonacci(n) {
    2 // Method 1: Using recursion
    3 if (n <= 1) return n;
    4 return fibonacci(n - 1) + fibonacci(n - 2);
    5
    6 // Method 2: Using loop (more efficient)
    7 // if (n <= 1) return n;
    8 // let prev = 0, curr = 1;
    9 // for(let i = 2; i <= n; i++) {
    10 // let next = prev + curr;
    11 // prev = curr;
    12 // curr = next;
    13 // }
    14 // return curr;
    15}
    16fibonacci(6); // Output: 8 (sequence: 0,1,1,2,3,5,8)
    17
  5. 5Find Missing Number in Array
    1function findMissingNumber(arr) {
    2 // Method 1: Using sum formula
    3 const n = arr.length + 1;
    4 const expectedSum = (n * (n + 1)) / 2;
    5 const actualSum = arr.reduce((sum, num) => sum + num, 0);
    6 return expectedSum - actualSum;
    7
    8 // Method 2: Using XOR
    9 // let xor = 0;
    10 // for(let i = 1; i <= arr.length + 1; i++) xor ^= i;
    11 // for(let num of arr) xor ^= num;
    12 // return xor;
    13}
    14findMissingNumber([1,2,4,5]); // Output: 3
    15
  6. 6Remove Duplicates from a String
    1function removeDuplicates(str) {
    2 // Method 1: Using Set
    3 return [...new Set(str)].join('');
    4
    5 // Method 2: Using object to track seen characters
    6 // let result = '';
    7 // const seen = {};
    8 // for(let char of str) {
    9 // if(!seen[char]) {
    10 // result += char;
    11 // seen[char] = true;
    12 // }
    13 // }
    14 // return result;
    15}
    16removeDuplicates("hello"); // Output: "helo"
  7. 7Find the First Non-Repeating Character
    1function firstNonRepeatingChar(str) {
    2 // Create frequency map
    3 const charCount = {};
    4 for(let char of str) {
    5 charCount[char] = (charCount[char] || 0) + 1;
    6 }
    7
    8 // Find first character with count 1
    9 for(let char of str) {
    10 if(charCount[char] === 1) {
    11 return char;
    12 }
    13 }
    14 return null;
    15}
    16firstNonRepeatingChar("leetcode"); // Output: "l"
  8. 8Count the Occurrences of Each Character
    1function countCharacters(str) {
    2 const charCount = {};
    3 for(let char of str) {
    4 charCount[char] = (charCount[char] || 0) + 1;
    5 }
    6 return charCount;
    7}
    8countCharacters("hello"); // Output: { h: 1, e: 1, l: 2, o: 1 }
  9. 9Reverse Words in a Sentence
    1function reverseWords(str) {
    2 // Method 1: Using built-in methods
    3 return str.split(' ').reverse().join(' ');
    4
    5 // Method 2: Manual implementation
    6 // let words = [];
    7 // let word = '';
    8 // for(let char of str) {
    9 // if(char === ' ') {
    10 // words.unshift(word);
    11 // word = '';
    12 // } else {
    13 // word += char;
    14 // }
    15 // }
    16 // words.unshift(word);
    17 // return words.join(' ');
    18}
    19reverseWords("Hello World"); // Output: "World Hello"
  10. 10Check if Two Strings are Anagrams
    1function areAnagrams(str1, str2) {
    2 // Remove spaces and convert to lowercase
    3 str1 = str1.replace(/s/g, '').toLowerCase();
    4 str2 = str2.replace(/s/g, '').toLowerCase();
    5
    6 // Method 1: Sort and compare
    7 return str1.split('').sort().join('') === str2.split('').sort().join('');
    8
    9 // Method 2: Character frequency comparison
    10 // if(str1.length !== str2.length) return false;
    11 // const charCount = {};
    12 // for(let char of str1) {
    13 // charCount[char] = (charCount[char] || 0) + 1;
    14 // }
    15 // for(let char of str2) {
    16 // if(!charCount[char]) return false;
    17 // charCount[char]--;
    18 // }
    19 // return true;
    20}
    21areAnagrams("listen", "silent"); // Output: true
  11. 11Find the Longest Substring Without Repeating Characters
    1function longestSubstringWithoutRepeating(str) {
    2 let maxLength = 0;
    3 let start = 0;
    4 const charMap = new Map();
    5
    6 for(let end = 0; end < str.length; end++) {
    7 if(charMap.has(str[end])) {
    8 start = Math.max(start, charMap.get(str[end]) + 1);
    9 }
    10 charMap.set(str[end], end);
    11 maxLength = Math.max(maxLength, end - start + 1);
    12 }
    13 return maxLength;
    14}
    15longestSubstringWithoutRepeating("abcabcbb"); // Output: 3
  12. 12Convert a String to an Integer (atoi Implementation)
    1function myAtoi(str) {
    2 const INT_MAX = 2147483647;
    3 const INT_MIN = -2147483648;
    4
    5 // Remove leading whitespace
    6 str = str.trim();
    7 if(!str) return 0;
    8
    9 let i = 0;
    10 let sign = 1;
    11 let result = 0;
    12
    13 // Handle sign
    14 if(str[i] === '+' || str[i] === '-') {
    15 sign = str[i] === '+' ? 1 : -1;
    16 i++;
    17 }
    18
    19 // Process digits
    20 while(i < str.length && /\d/.test(str[i])) {
    21 result = result * 10 + (str[i] - '0');
    22 if(sign === 1 && result > INT_MAX) return INT_MAX;
    23 if(sign === -1 && -result < INT_MIN) return INT_MIN;
    24 i++;
    25 }
    26
    27 return sign * result;
    28}
    29myAtoi("42"); // Output: 42
    30myAtoi(" -42"); // Output: -42
  13. 13Compress a String (Run-Length Encoding)
    1function compressString(str) {
    2 if(!str) return "";
    3
    4 let result = "";
    5 let count = 1;
    6 let currentChar = str[0];
    7
    8 for(let i = 1; i <= str.length; i++) {
    9 if(str[i] === currentChar) {
    10 count++;
    11 } else {
    12 result += currentChar + count;
    13 currentChar = str[i];
    14 count = 1;
    15 }
    16 }
    17
    18 return result.length < str.length ? result : str;
    19}
    20compressString("aabbbcccc"); // Output: "a2b3c4"
  14. 14Find the Most Frequent Character
    1function findMostFrequentChar(str) {
    2 const charCount = {};
    3 let maxChar = '';
    4 let maxCount = 0;
    5
    6 // Count character frequencies
    7 for(let char of str) {
    8 charCount[char] = (charCount[char] || 0) + 1;
    9 if(charCount[char] > maxCount) {
    10 maxChar = char;
    11 maxCount = charCount[char];
    12 }
    13 }
    14 return maxChar;
    15}
    16findMostFrequentChar("hello world"); // Output: "l"
  15. 15Find All Substrings of a Given String
    1function findAllSubstrings(str) {
    2 const substrings = [];
    3
    4 // Generate all possible substrings
    5 for(let i = 0; i < str.length; i++) {
    6 for(let j = i + 1; j <= str.length; j++) {
    7 substrings.push(str.slice(i, j));
    8 }
    9 }
    10 return substrings;
    11}
    12findAllSubstrings("abc"); // Output: ["a", "ab", "abc", "b", "bc", "c"]
  16. 16Check if a String is a Rotation of Another String
    1function isRotation(str1, str2) {
    2 // Check if lengths are equal and not empty
    3 if(str1.length !== str2.length || !str1.length) return false;
    4
    5 // Concatenate str1 with itself and check if str2 is substring
    6 return (str1 + str1).includes(str2);
    7}
    8isRotation("hello", "llohe"); // Output: true
    9isRotation("hello", "world"); // Output: false
  17. 17Remove All White Spaces from a String
    1function removeWhitespace(str) {
    2 // Method 1: Using regex
    3 return str.replace(/\s/g, '');
    4
    5 // Method 2: Using split and join
    6 // return str.split(' ').join('');
    7
    8 // Method 3: Using filter
    9 // return [...str].filter(char => char !== ' ').join('');
    10}
    11removeWhitespace("hello world js"); // Output: "helloworldjs"
  18. 18Check if a String is a Valid Shuffle of Two Strings
    1function isValidShuffle(str1, str2, result) {
    2 // Check if lengths match
    3 if(str1.length + str2.length !== result.length) return false;
    4
    5 // Convert strings to arrays and sort them
    6 const sortedResult = [...result].sort().join('');
    7 const sortedExpected = [...str1 + str2].sort().join('');
    8
    9 return sortedResult === sortedExpected;
    10}
    11isValidShuffle("abc", "def", "abcdef"); // Output: true
    12isValidShuffle("abc", "def", "abdecf"); // Output: true
    13isValidShuffle("abc", "def", "abcxyz"); // Output: false
  19. 19Convert a String to Title Case
    1function toTitleCase(str) {
    2 return str
    3 .toLowerCase()
    4 .split(' ')
    5 .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    6 .join(' ');
    7}
    8toTitleCase("hello world js"); // Output: "Hello World Js"
  20. 20Find the Longest Common Prefix
    1function longestCommonPrefix(strs) {
    2 if(!strs.length) return "";
    3
    4 let prefix = strs[0];
    5 for(let i = 1; i < strs.length; i++) {
    6 while(strs[i].indexOf(prefix) !== 0) {
    7 prefix = prefix.slice(0, -1);
    8 if(!prefix) return "";
    9 }
    10 }
    11 return prefix;
    12}
    13longestCommonPrefix(["flower", "flow", "flight"]); // Output: "fl"
  21. 21Convert a String to a Character Array
    1function stringToCharArray(str) {
    2 // Method 1: Using spread operator
    3 return [...str];
    4
    5 // Method 2: Using split
    6 // return str.split('');
    7
    8 // Method 3: Using Array.from
    9 // return Array.from(str);
    10}
    11stringToCharArray("hello"); // Output: ['h', 'e', 'l', 'l', 'o']
  22. 22Replace Spaces with %20 (URL Encoding)
    1function urlEncode(str) {
    2 // Method 1: Using encodeURIComponent
    3 return encodeURIComponent(str);
    4
    5 // Method 2: Manual replacement
    6 // return str.replace(/\s/g, '%20');
    7}
    8urlEncode("hello world js"); // Output: "hello%20world%20js"
  23. 23Convert a Sentence into an Acronym
    1function createAcronym(str) {
    2 return str
    3 .split(' ')
    4 .map(word => word.charAt(0).toUpperCase())
    5 .join('');
    6}
    7createAcronym("World Health Organization"); // Output: "WHO"
  24. 24Check if a String Contains Only Digits
    1function containsOnlyDigits(str) {
    2 // Method 1: Using regex
    3 return /^\d+$/.test(str);
    4
    5 // Method 2: Using every
    6 // return [...str].every(char => char >= '0' && char <= '9');
    7}
    8containsOnlyDigits("12345"); // Output: true
    9containsOnlyDigits("123a45"); // Output: false
  25. 25Find the Number of Words in a String
    1function countWords(str) {
    2 // Method 1: Split and filter
    3 return str.trim().split(/\s+/).filter(Boolean).length;
    4
    5 // Method 2: Using match
    6 // return (str.trim().match(/\S+/g) || []).length;
    7}
    8countWords(" Hello world JS "); // Output: 3
  26. 26Remove a Given Character from a String
    1function removeCharacter(str, char) {
    2 // Method 1: Using replace
    3 return str.replace(new RegExp(char, 'g'), '');
    4
    5 // Method 2: Using split and join
    6 // return str.split(char).join('');
    7}
    8removeCharacter("hello world", "l"); // Output: "heo word"
  27. 27Find the Shortest Word in a String
    1function findShortestWord(str) {
    2 return str
    3 .split(' ')
    4 .reduce((shortest, current) =>
    5 current.length < shortest.length ? current : shortest
    6 );
    7}
    8findShortestWord("The quick brown fox"); // Output: "The"
  28. 28Find the Longest Palindromic Substring
    1function longestPalindromicSubstring(str) {
    2 let start = 0;
    3 let maxLength = 1;
    4
    5 function expandAroundCenter(left, right) {
    6 while(left >= 0 && right < str.length && str[left] === str[right]) {
    7 const currentLength = right - left + 1;
    8 if(currentLength > maxLength) {
    9 start = left;
    10 maxLength = currentLength;
    11 }
    12 left--;
    13 right++;
    14 }
    15 }
    16
    17 for(let i = 0; i < str.length; i++) {
    18 expandAroundCenter(i, i); // Odd length palindromes
    19 expandAroundCenter(i, i + 1); // Even length palindromes
    20 }
    21
    22 return str.substring(start, start + maxLength);
    23}
    24longestPalindromicSubstring("babad"); // Output: "bab" or "aba"
    25longestPalindromicSubstring("cbbd"); // Output: "bb"
  29. 29Count Vowels in String
    1function countVowels(str) {
    2 // Convert string to lowercase for easier checking
    3 str = str.toLowerCase();
    4 let count = 0;
    5 const vowels = ['a', 'e', 'i', 'o', 'u'];
    6
    7 // Method 1: Using loop
    8 for(let char of str) {
    9 if(vowels.includes(char)) {
    10 count++;
    11 }
    12 }
    13 return count;
    14
    15 // Method 2: Using regex
    16 // return str.match(/[aeiou]/gi)?.length || 0;
    17}
    18countVowels("JavaScript"); // Output: 3
    19
  30. 30Find Maximum Number in Array
    1function findMax(arr) {
    2 // Method 1: Using Math.max()
    3 return Math.max(...arr);
    4
    5 // Method 2: Using loop
    6 // let max = arr[0];
    7 // for(let i = 1; i < arr.length; i++) {
    8 // if(arr[i] > max) {
    9 // max = arr[i];
    10 // }
    11 // }
    12 // return max;
    13}
    14findMax([5, 12, 3, 8, 9]); // Output: 12
    15
  31. 31Check if Number is Prime
    1function isPrime(num) {
    2 // Handle edge cases
    3 if(num <= 1) return false;
    4 if(num <= 3) return true;
    5
    6 // Check for divisibility up to square root
    7 for(let i = 2; i <= Math.sqrt(num); i++) {
    8 if(num % i === 0) {
    9 return false;
    10 }
    11 }
    12 return true;
    13}
    14isPrime(17); // Output: true
    15isPrime(4); // Output: false
    16
  32. 32Remove Duplicates from Array
    1function removeDuplicates(arr) {
    2 // Method 1: Using Set
    3 return [...new Set(arr)];
    4
    5 // Method 2: Using filter
    6 // return arr.filter((item, index) => arr.indexOf(item) === index);
    7
    8 // Method 3: Using reduce
    9 // return arr.reduce((unique, item) =>
    10 // unique.includes(item) ? unique : [...unique, item],
    11 // []);
    12}
    13removeDuplicates([1, 2, 2, 3, 3, 4, 5, 5]); // Output: [1, 2, 3, 4, 5]
    14
  33. 33Capitalize First Letter of Each Word
    1function capitalizeWords(str) {
    2 // Method 1: Using map
    3 return str
    4 .split(' ')
    5 .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    6 .join(' ');
    7
    8 // Method 2: Using replace
    9 // return str.replace(/\b\w/g, char => char.toUpperCase());
    10}
    11capitalizeWords("hello world"); // Output: "Hello World"
    12
  34. 34Sum of Array Elements
    1function arraySum(arr) {
    2 // Method 1: Using reduce
    3 return arr.reduce((sum, num) => sum + num, 0);
    4
    5 // Method 2: Using forEach
    6 // let sum = 0;
    7 // arr.forEach(num => sum += num);
    8 // return sum;
    9
    10 // Method 3: Using for...of
    11 // let sum = 0;
    12 // for(let num of arr) {
    13 // sum += num;
    14 // }
    15 // return sum;
    16}
    17arraySum([1, 2, 3, 4, 5]); // Output: 15
    18

Share this article

Last updated: July 14, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕