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:
- Two-Pointer Technique: Check characters from both directions.
- Early Exit: Stop as soon as a mismatch is found.
- 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));
}
}
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)
andstring.charAt(j)
) and incrementi
and decrementj
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"
returnstrue
.Even-length Palindrome:
"abccba"
returnstrue
.Non-Palindrome:
"asfgsa"
returnsfalse
.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
- Java Fundamentals
- Array Interview Essentials
- Java Memory Essentials
- Java Keywords Essentials
- Java OOPs Essentials
- Collections Framework Essentials
Happy Coding!
Top comments (2)
how about:
String oddString = "abcdcba";
StringBuilder sb = new StringBuilder(oddString);
oddString.equals(sb.reverse().toString())
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.