Write a function named isPalindrome that determines whether a given string is a palindrome.

A palindrome is a word, phrase, or sequence that reads the same backward as forward, ignoring case and non-alphanumeric characters.

Example 1

Input
s (string) = madam
Returns (boolean) true

Example 2

Input
s (string) = hello
Returns (boolean) false

Example 3

Input
s (string) = A man, a plan, a canal, Panama
Returns (boolean) true

Example 4

Input
s (string) = No lemon, no melon
Returns (boolean) true

A string is considered a palindrome if it reads the same forward and backward, ignoring spaces, punctuation, and capitalization. To check if a string is a palindrome, first sanitize it by removing unwanted characters and converting it to the same case. Then, compare the sanitized string with its reverse.

To check if a string is a palindrome without using built-in reverse functions, follow these steps:

  1. Check for Empty or Null Input
    If the string is empty or null, return true directly or handle it as a special case (empty strings are generally considered palindromes).

  2. Sanitize the String
    Ignore spaces, punctuation, and capitalization:

    • Remove all non-alphanumeric characters.

    • Convert all characters to lowercase.

  3. Compare Characters from Both Ends
    Use a loop with two pointers:

    • One starting from the beginning.

    • One from the end.
      Compare corresponding characters while moving inward.

  4. Return Result
    If all characters match, return true; otherwise, return false.

Pseudocode:

Function isPalindrome(s):
    Initialize an empty string cleanString
    For each character ch in s:
        If ch is alphanumeric:
            Append lowercase of ch to cleanString

    Set reversedString = reverse of cleanString

    If cleanString is equal to reversedString:
        Return true
    Else:
        Return false
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.