CodingEasy Strings

Valid Palindrome

Asked for all developer roles

Why they ask this: Tests the two-pointer technique and careful handling of edge cases like spaces and punctuation.

Problem

A phrase is a palindrome if, after converting all letters to lowercase and removing every non-alphanumeric character, it reads the same forwards and backwards. Return true if the string s is a palindrome, otherwise false.

Example 1

text
Input:  "A man, a plan, a canal: Panama"
Output: true    // "amanaplanacanalpanama"

Example 2

text
Input:  "race a car"
Output: false   // "raceacar"

Example 3

text
Input:  " "
Output: true    // empty string after cleaning

Hints

    Approach

    1. Lowercase the string and remove everything except a-z and 0-9.
    2. Put left at the start and right at the end. While left < right, if the characters differ return false; otherwise move both pointers inwards.
    3. If the loop finishes, return true.

    Follow-up: you can avoid the cleaned copy (O(1) extra space) by skipping non-alphanumeric characters with the pointers directly on the original string.

    Solution

    js
    function isPalindrome(s) {
      const clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
      let left = 0;
      let right = clean.length - 1;
    
      while (left < right) {
        if (clean[left] !== clean[right]) return false;
        left++;
        right--;
      }
    
      return true;
    }
    
    console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
    console.log(isPalindrome('race a car'));                     // false
    Time O(n) Space O(n)

    Can you explain this in your own words?

    Back to coding practice