Top 10 JavaScript Algorithms for Coding Challenges

Top 10 JavaScript Algorithms for Coding Challenges with Code Examples

Introduction

JavaScript is a versatile language widely used in web development, and mastering its algorithms is crucial for tackling coding challenges and technical interviews. This blog post will cover the top 10 JavaScript algorithms that are frequently encountered in coding challenges, complete with code examples to help you understand and implement them effectively.

1. Reverse a String

Reversing a string is a common task that tests your understanding of string manipulation.

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

console.log(reverseString("hello")); // Output: "olleh"

2. Palindrome Check

A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward.

function isPalindrome(str) {
    const cleanedStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
    return cleanedStr === cleanedStr.split('').reverse().join('');
}

console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true

3. Find the Most Frequent Character

This algorithm identifies the most frequently occurring character in a string.

function maxChar(str) {
    const charMap = {};
    let max = 0;
    let maxChar = '';

    for (let char of str) {
        charMap[char] = charMap[char] + 1 || 1;
    }

    for (let char in charMap) {
        if (charMap[char] > max) {
            max = charMap[char];
            maxChar = char;
        }
    }

    return maxChar;
}

console.log(maxChar("javascript")); // Output: "a"

4. Array Chunking

Chunking an array involves splitting it into smaller arrays of a specified size.

function chunkArray(array, size) {
    const chunked = [];
    let index = 0;

    while (index < array.length) {
        chunked.push(array.slice(index, index + size));
        index += size;
    }

    return chunked;
}

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

5. Title Case a Sentence

Transform a string so that the first letter of each word is capitalized.

function titleCase(str) {
    return str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}

console.log(titleCase("i am learning javascript")); // Output: "I Am Learning Javascript"

6. Check for Anagrams

Determine if two strings are anagrams of each other.

function isAnagram(str1, str2) {
    const cleanStr = str => str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
    return cleanStr(str1) === cleanStr(str2);
}

console.log(isAnagram("listen", "silent")); // Output: true

7. Count Vowels

Count the number of vowels in a given string.

function countVowels(str) {
    const vowels = 'aeiou';
    let count = 0;

    for (let char of str.toLowerCase()) {
        if (vowels.includes(char)) {
            count++;
        }
    }

    return count;
}

console.log(countVowels("hello world")); // Output: 3

8. FizzBuzz

A classic problem that outputs "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.

function fizzBuzz(n) {
    for (let i = 1; i <= n; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
            console.log("FizzBuzz");
        } else if (i % 3 === 0) {
            console.log("Fizz");
        } else if (i % 5 === 0) {
            console.log("Buzz");
        } else {
            console.log(i);
        }
    }
}

fizzBuzz(15);
// Output: 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"

9. Steps String Pattern

Create a step-like pattern using strings.

function steps(n) {
    for (let i = 1; i <= n; i++) {
        console.log('#'.repeat(i) + ' '.repeat(n - i));
    }
}

steps(4);
// Output:
// "#   "
// "##  "
// "### "
// "####"

10. Pyramid String Pattern

Build a pyramid with strings.

function pyramid(n) {
    const midpoint = Math.floor((2 * n - 1) / 2);

    for (let row = 0; row < n; row++) {
        let level = '';

        for (let column = 0; column <= 2 * n - 1; column++) {
            if (midpoint - row <= column && midpoint + row >= column) {
                level += '#';
            } else {
                level += ' ';
            }
        }

        console.log(level);
    }
}

pyramid(3);
// Output:
// "  #  "
// " ### "
// "#####"

Conclusion

Mastering these top 10 JavaScript algorithms will not only prepare you for coding challenges and technical interviews but also enhance your problem-solving skills. Practice these algorithms regularly, and you'll find yourself more confident and capable in tackling a wide range of coding problems.

Post a Comment

Previous Post Next Post