DEV Community

Cover image for Strings: Checking for Palindromes
Arshi Saxena
Arshi Saxena

Posted on

1 3 1 1 2

Strings: Checking for Palindromes

In this post, we’ll walk through a common interview question—checking if a given string is a palindrome. This problem is a great exercise for understanding pointers, loops, and conditional logic in Java.


Problem Statement

Write a Java method that checks if a given string is a palindrome. A palindrome is a word or phrase that reads the same forwards and backwards (e.g., “noon” or “madam”).


Solution Overview

The solution leverages a two-pointer technique to check characters from both ends of the string, moving towards the center. By comparing characters at corresponding positions, we can determine if the string is a palindrome without having to reverse it.

Key Points of the Approach:

  1. Two-Pointer Technique: Check characters from both directions.
  2. Early Exit: Stop as soon as a mismatch is found.
  3. Optimization: Only traverse up to half the string length for efficiency.

Code Solution

Here’s the code for the solution:

public class StringPalindromeQuestion {

    // Method to check if a given string is a palindrome
    private boolean isPalindrome(String string) {
        if (string != null) {
            for (int i = 0, j = string.length() - 1; i < string.length()
            / 2; i++, j--) {
                if (string.charAt(i) != string.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        StringPalindromeQuestion palindrome = new StringPalindromeQuestion();

        String oddString = "abcdcba";    // Palindrome with odd length
        String evenString = "abccba";    // Palindrome with even length
        String nonPalindrome = "asfgsa"; // Not a palindrome

        // Result: true
        System.out.println(palindrome.isPalindrome(oddString));

        // Result: true
        System.out.println(palindrome.isPalindrome(evenString));

        // Result: false
        System.out.println(palindrome.isPalindrome(nonPalindrome));

        // Testing with null
        // Result: true
        System.out.println(palindrome.isPalindrome(null));
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

1. Two-Pointer Approach:

  • We initialize two pointers: one at the start (i) and one at the end (j).

  • We compare characters at these positions (string.charAt(i) and string.charAt(j)) and increment i and decrement j after each comparison.

  • The loop runs only up to string.length() / 2, ensuring efficient traversal regardless of whether the length is odd or even.

2. Odd vs. Even Length:

  • For even-length strings (e.g., "abccba"), the method checks up to the midpoint, so no middle character remains unchecked.

  • For odd-length strings (e.g., "abcdcba"), the middle character naturally does not affect palindrome status.

3. Null Handling:
The method checks if the string is null at the beginning to avoid NullPointerException.

Example Output

  • Odd-length Palindrome: "abcdcba" returns true.

  • Even-length Palindrome: "abccba" returns true.

  • Non-Palindrome: "asfgsa" returns false.

  • Null String: returns true (a null input is considered a palindrome by this implementation).


Interview Tip 💡

Understanding two-pointer techniques is valuable for solving many string-based problems efficiently. This technique avoids extra space complexity and makes code execution faster by limiting unnecessary comparisons.


Conclusion

This solution provides a clean and efficient way to check for palindromes in Java. Try using this approach with different string inputs to further solidify your understanding of pointer manipulation and string traversal.


Related Posts

Happy Coding!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
shshlomy profile image
shlomy sheps

how about:
String oddString = "abcdcba";
StringBuilder sb = new StringBuilder(oddString);
oddString.equals(sb.reverse().toString())

Collapse
 
arshisaxena26 profile image
Arshi Saxena

Thank you for suggesting the StringBuilder approach! It’s a great alternative for simple, readable code, especially for shorter strings. I opted for the iterative approach in this article to address a few memory and performance considerations:

  • Memory Efficiency: Using StringBuilder requires creating a new reversed string object, effectively doubling memory use for the comparison. For larger strings or frequent palindrome checks, this can lead to memory waste.

  • Performance: The StringBuilder approach reverse the entire string every time, processing each character to create a reversed version, regardless of whether it’s a palindrome. The iterative approach, however, stops as soon as a mismatch is found (if any), which means it may only process half the string. This can be especially beneficial for non-palindromic inputs, where the mismatch could be found quickly.

While StringBuilder offers a neat one-liner solution, the iterative method helps avoid potential memory and performance costs for cases where efficiency is crucial.

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay