Skip to main content

Command Palette

Search for a command to run...

JavaScript String Coding Interview Questions

Published
4 min readView as Markdown
M

"Hello, I'm Moiz Qureshi, a dedicated Full Stack Developer with over 4 years of hands-on experience in the dynamic realms of .NET, React, and Next.js technologies. My journey in web development has been marked by a relentless pursuit of excellence, where I have honed my skills in creating robust and innovative solutions.

My passion for technology extends beyond my work, as I am committed to staying on the cutting edge of the ever-evolving tech landscape. Embracing challenges and leveraging emerging trends, I thrive on continuous learning to ensure my skills are always at the forefront.

In my posts, I share insights from my experiences, dive into the latest industry trends, and explore the fascinating intersection of coding and creativity. Join me on this exciting journey as we navigate the ever-changing world of web development together.

Let's connect, collaborate, and explore the limitless possibilities of technology. Welcome to my corner of the digital universe!"

Here are 15 coding interview questions related to strings in JavaScript, along with sample solutions:

  1. Reverse a String: Write a function to reverse a string in-place.

     function reverseString(str) {
         return str.split('').reverse().join('');
     }
    
  2. Check for Palindrome: Determine if a given string is a palindrome.

     function isPalindrome(str) {
         const reversed = str.split('').reverse().join('');
         return str === reversed;
     }
    
  3. Find the First Non-Repeated Character: Write a function to find the first non-repeated character in a string.

     function firstNonRepeatedChar(str) {
         for (let char of str) {
             if (str.indexOf(char) === str.lastIndexOf(char)) {
                 return char;
             }
         }
         return null;
     }
    
  4. Anagrams: Check if two strings are anagrams of each other.

     function areAnagrams(str1, str2) {
         return str1.split('').sort().join('') === str2.split('').sort().join('');
     }
    
  5. Count Vowels: Write a function to count the number of vowels in a string.

     function countVowels(str) {
         const vowels = 'aeiouAEIOU';
         return str.split('').filter(char => vowels.includes(char)).length;
     }
    
  6. String Compression: Implement a basic string compression algorithm.

     function compressString(str) {
         let compressed = '';
         let count = 1;
    
         for (let i = 0; i < str.length; i++) {
             if (str[i] === str[i + 1]) {
                 count++;
             } else {
                 compressed += str[i] + count;
                 count = 1;
             }
         }
    
         return compressed.length < str.length ? compressed : str;
     }
    
  7. Reverse Words in a String: Reverse the order of words in a given string.

     function reverseWords(str) {
         return str.split(' ').reverse().join(' ');
     }
    
  8. Longest Substring Without Repeating Characters: Find the length of the longest substring without repeating characters.

     function lengthOfLongestSubstring(s) {
         let longest = 0;
         let start = 0;
         const charIndexMap = {};
    
         for (let end = 0; end < s.length; end++) {
             if (charIndexMap[s[end]] !== undefined) {
                 start = Math.max(charIndexMap[s[end]] + 1, start);
             }
    
             charIndexMap[s[end]] = end;
             longest = Math.max(longest, end - start + 1);
         }
    
         return longest;
     }
    
  9. Implement strStr(): Implement the strStr() function, which finds the first occurrence of a substring in another string.

     function strStr(haystack, needle) {
         if (needle === '') return 0;
    
         for (let i = 0; i < haystack.length - needle.length + 1; i++) {
             if (haystack.slice(i, i + needle.length) === needle) {
                 return i;
             }
         }
    
         return -1;
     }
    
  10. Valid Parentheses: Determine if a given string of parentheses is valid.

    function isValidParentheses(s) {
        const stack = [];
        const parenthesesMap = { ')': '(', '}': '{', ']': '[' };
    
        for (let char of s) {
            if (['(', '{', '['].includes(char)) {
                stack.push(char);
            } else {
                if (stack.pop() !== parenthesesMap[char]) {
                    return false;
                }
            }
        }
    
        return stack.length === 0;
    }
    
  11. String to Integer (atoi): Implement the atoi function, which converts a string to an integer.

    function atoi(str) {
        const INT_MAX = 2**31 - 1;
        const INT_MIN = -2**31;
        let result = parseInt(str) || 0;
    
        if (result > INT_MAX) return INT_MAX;
        if (result < INT_MIN) return INT_MIN;
    
        return result;
    }
    
  12. Implement a Basic Calculator: Implement a basic calculator to evaluate a simple expression string containing non-negative integers, '+', '-', '*', and '/' operators.

    function calculate(s) {
        return Function('"use strict";return (' + s + ')')();
    }
    
  13. Minimum Window Substring: Find the minimum window in a string that contains all characters of another string.

    function minWindow(s, t) {
        const charCount = {};
        let start = 0;
        let minLen = Infinity;
        let minWindow = '';
    
        for (let char of t) {
            charCount[char] = (charCount[char] || 0) + 1;
        }
    
        let requiredChars = Object.keys(charCount).length;
        let formedChars = 0;
    
        for (let end = 0; end < s.length; end++) {
            if (charCount[s[end]] !== undefined) {
                charCount[s[end]]--;
                if (charCount[s[end]] === 0) formedChars++;
            }
    
            while (formedChars === requiredChars) {
                if (end - start + 1 < minLen) {
                    minLen = end - start + 1;
                    minWindow = s.slice(start, end + 1);
                }
    
                if (charCount[s[start]] !== undefined) {
                    charCount[s[start]]++;
                    if (charCount[s[start]] > 0) formedChars--;
                }
    
                start++;
            }
        }
    
        return minWindow;
    }
    
  14. ZigZag Conversion: Convert a string to a zigzag pattern with a given number of rows.

    function convert(s, numRows) {
        if (numRows === 1 || numRows >= s.length) return s;
    
        const rows = Array.from({ length: numRows }, () => '');
        let currentRow = 0;
        let direction = 1;
    
        for (let char of s) {
            rows[currentRow] += char;
    
            if (currentRow === 0) direction = 1;
            if (currentRow === numRows - 1) direction = -1;
    
            currentRow += direction;
        }
    
        return rows.join('');
    }
    
  15. Group Anagrams: Given an array of strings, group anagrams together.

    function groupAnagrams(strs) {
        const anagramMap = new Map();
    
        for (let str of strs) {
            const sortedStr = str.split('').sort().join('');
            if (!anagramMap.has(sortedStr)) {
                anagramMap.set(sortedStr, [str]);
            } else {
                anagramMap.get(sortedStr).push(str); } }
    
    return Array.from(anagramMap.values()); }
    

These questions cover a range of string manipulation and algorithmic concepts commonly encountered in coding interviews.