Skip to content

Instantly share code, notes, and snippets.

@MunimIftikhar
Last active November 8, 2022 18:27
Show Gist options
  • Select an option

  • Save MunimIftikhar/c096c47a5a376fff4012b616f4d55d72 to your computer and use it in GitHub Desktop.

Select an option

Save MunimIftikhar/c096c47a5a376fff4012b616f4d55d72 to your computer and use it in GitHub Desktop.
freeCodeCamp: Palindrome Checker

Problem Statement

Return true if the given string is a palindrome. Otherwise, return false.

A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

Note: You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.

We'll pass strings with varying formats, such as racecar, RaceCar, and race CAR among others.

We'll also pass strings with special symbols, such as 2A3*3a2, 2A3 3a2, and 2_A3*3#A2.

Constraints

  • str can consist of English lower or uppercase letters.
  • str can consist of numbers, English lower or uppercase letters and special characters.
  • str can also have spaces

Input example #1

"racecar"

Expected output #1

true

Input example #2

"race CAR"

Expected output #2

true

Input example #3

"2A3*3a2"

Expected output #3

true

Input example #4

"_cat"

Expected output #4

false

Solution code

// Solution function
function palindrome(str) {
    // Convert given string to lower case english letters and extract the valid 
    // string exclusing the special characters using the regular expression
    let lowerMatchedStr = str.toLowerCase().match(/[A-Za-z0-9]+/g);
    // Join the matched string array
    let testStr = lowerMatchedStr.join("");
    /* 
        Use two pointers to move in a string
            1. firstPointer to iterate from start to end
            2. secondPointer to iterate from end to start
    */
    let secondPointer = testStr.length - 1;
    // Loop through the testStr
    for (let firstPointer = 0; firstPointer < testStr.length; firstPointer++) {
        // Check if character from the start and the end is same
        if (testStr[firstPointer] != testStr[secondPointer]) {
            return false;
        }
        // Break the loop if first and second pointer meet eachother
        if (firstPointer == secondPointer) {
            break;
        }
        // Decrement the secondPointer
        secondPointer--;
    }
    // Return true if the string is a palindrome
    return true;
}

// Check solution function
console.log(palindrome("1 eye for of 1 eye."));

Problem link

freeCodeCamp Palindrome Checker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment