Solving the Palindrome Checker Problem: From Basic to Optimized Solutions

Introduction

Palindromes are fascinating! Whether it's a word, phrase, or number, a palindrome reads the same backward as forward. In this blog post, we'll tackle the Palindrome Checker problem, starting with a basic solution and refining it to meet professional standards. By the end, you'll have a clear understanding of how to solve this problem efficiently and handle edge cases like a pro.


Problem Statement

Write a function that checks if a given word or phrase is a palindrome. A palindrome is a string that reads the same backward as forward, ignoring spaces, punctuation, and case.

Examples

  1. "racecar"true

  2. "A man, a plan, a canal, Panama"true

  3. "hello world"false

  4. "12321"true

  5. "No lemon, no melon"true


Constraints

  1. The input can contain:

    • Uppercase and lowercase letters.

    • Spaces and punctuation.

    • Numbers.

  2. The solution should be case-insensitive.

  3. Spaces and non-alphanumeric characters should be ignored.

  4. The function should handle edge cases, such as empty strings or strings with only spaces.


Initial Logic

To solve this problem, I broke it down into the following steps:

  1. Normalize the Input:

    • Convert the string to lowercase to make the check case-insensitive.

    • Remove spaces and non-alphanumeric characters.

  2. Reverse the String:

    • Create a reversed version of the normalized string.
  3. Compare the Strings:

    • If the normalized string and its reversed version are the same, it's a palindrome.

Initial Code

Here’s the first version of the code I wrote:

import java.util.Scanner;

public class PalindromeChecker {
    public static void checker() {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter word or phrase: ");
        String mytext = scanner.nextLine();

        // Normalize the input: lowercase and remove spaces
        String palindrome = mytext.toLowerCase().replace(" ", "");
        String reversedPalindrome = "";

        // Reverse the string
        for (int i = palindrome.length() - 1; i >= 0; i--) {
            reversedPalindrome += palindrome.charAt(i);
        }

        // Check if it's a palindrome
        if (reversedPalindrome.equals(palindrome)) {
            System.out.println("The word/phrase \"" + mytext + "\" is a palindrome.");
        } else {
            System.out.println("The word/phrase \"" + mytext + "\" is not a palindrome.");
        }

        scanner.close();
    }
}

Explanation of the Initial Code

  1. Input Handling:

    • The program reads the user’s input using Scanner.
  2. Normalization:

    • The input is converted to lowercase and spaces are removed using toLowerCase() and replace(" ", "").
  3. Reversing the String:

    • A for loop iterates through the string in reverse order and builds the reversed string using +=.
  4. Palindrome Check:

    • The program compares the normalized string with its reversed version using equals().

Limitations of the Initial Code

While the initial solution works for basic cases, it has some limitations:

  1. Inefficient String Concatenation:

    • Using += to build the reversed string is inefficient because strings are immutable in Java, and each concatenation creates a new object.
  2. No Edge Case Handling:

    • The code does not handle empty strings, strings with only spaces, or non-alphanumeric characters.
  3. Hardcoded Input:

    • The program relies on Scanner for input, making it less reusable.

Improved Version

Here’s the improved version of the code, addressing the limitations:


public class palindromeChecker {
  public static boolean checker( String inputString ) {
    if (inputString == null || inputString.trim().isEmpty()) {
      return false;
    }
    String palindrome = inputString.toLowerCase().replaceAll("[^a-z0-9]", "");
    // Reverse the string using StringBuilder
    StringBuilder reversedPalindrome = new StringBuilder(palindrome).reverse();
    // Compare the normalized input with its reversed version
    return palindrome.equals(reversedPalindrome.toString());

  }
}

Why the Improved Version is Better

  1. Efficient String Reversal:

    • Uses StringBuilder.reverse() for efficient string reversal, avoiding the inefficiency of +=.
  2. Edge Case Handling:

    • Handles null, empty strings, and strings with only spaces.

    • Removes non-alphanumeric characters using replaceAll("[^a-z0-9]", "").

  3. Reusable Method:

    • The isPalindrome method takes a string as input and returns a boolean, making it reusable and testable.

Conclusion

Solving the Palindrome Checker problem taught me the importance of writing efficient, reusable, and robust code. By refining my initial solution, I learned how to handle edge cases, optimize performance, and write clean, professional code. Whether you're preparing for an interview or just sharpening your coding skills, this problem is a great way to practice!