Java String Program · S02
Check If a String Is a Palindrome in Java
A palindrome reads the same forwards and backwards. Compare characters from both ends, stop at the first mismatch, and learn why two pointers beat building a reversed copy.
Problem Statement
Write a method isPalindrome(String s) that returns true if s reads the same forwards and backwards, otherwise false.
The comparison is exact: it is case-sensitive, and spaces and punctuation count as characters. An empty string and a single character are palindromes, and null returns false.
Input/Output Examples
"level"OutputtrueExplanation: the pairs l/l and e/e match, and the middle v needs no partner."abca"OutputfalseExplanation: the outer pair a/a matches, but the inner pair b/c does not."Madam"OutputfalseExplanation: M and m are different characters under the exact comparison.Visual Explanation
- Step 1left = 0, right = 4levelcompare l and l match, move inwards
- Step 2left = 1, right = 3levelcompare e and e match, move inwards
- Step 3left = 2, right = 2levelleft < right is false middle needs no check
- Doneno mismatch foundtrue
"level" with two pointers: the compared pair is highlighted (amber), checked characters fade, and the loop stops when the pointers meet in the middle (purple).Each step compares one pair from the outside in. A single mismatch would end the loop with false immediately; here every pair matches, so the method returns true after only two comparisons.
Approaches
All three approaches use the same fact: character i must equal character n - 1 - i. They differ in how much memory they need.
Approach 1: Two Pointers (Recommended)
Idea: compare characters from both ends with a loop, moving the pointers towards the middle.
- Set
left = 0andright = s.length() - 1. - While
left < right, compares.charAt(left)ands.charAt(right). - If they differ, return
false; otherwise, move both pointers one step inwards. - When the pointers meet or cross, return
true.
Time: O(n) · Space: O(1).
Approach 2: Reverse and Compare
Idea: a palindrome equals its own reverse, so build the reverse with StringBuilder and compare.
- Create a
StringBuilderfromsand callreverse(). - Convert the result to a
String. - Return
reversed.equals(s).
Time: O(n) · Space: O(n). It always builds a full reversed copy, even when the first pair already differs.
Approach 3: Recursion
Idea: a string is a palindrome if its outer characters match and the part between them is also a palindrome.
- Call a helper with
left = 0andright = n - 1. - If
left >= right, returntrue. - If the outer characters differ, return
false; otherwise, recurse withleft + 1andright - 1.
Time: O(n) · Space: O(n). Each matched pair adds a stack frame, so very long strings can throw StackOverflowError.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. All three programs print the same output for the same inputs.
Approach 1: Two Pointers (Recommended)
No copy of the string is made, and the loop stops at the first mismatch. The condition left < right skips the middle character of an odd-length string.
public class PalindromeTwoPointers {
// Compares characters from both ends and moves towards the middle
static boolean isPalindrome(String s) {
if (s == null) {
return false;
}
int left = 0;
int right = s.length() - 1;
while (left < right) { // the middle character never needs a check
if (s.charAt(left) != s.charAt(right)) {
return false; // first mismatch decides the answer
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String[] inputs = {"level", "noon", "", "a", "Madam", "abca"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + isPalindrome(s));
}
}
}
"level" -> true "noon" -> true "" -> true "a" -> true "Madam" -> false "abca" -> false
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Reverse and Compare
The shortest solution and hard to get wrong, but it allocates a second string of the same length.
public class PalindromeReverse {
// Builds a reversed copy of the string and compares it with the original
static boolean isPalindrome(String s) {
if (s == null) {
return false; // no string, so no palindrome
}
String reversed = new StringBuilder(s).reverse().toString();
return reversed.equals(s);
}
public static void main(String[] args) {
String[] inputs = {"level", "noon", "", "a", "Madam", "abca"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + isPalindrome(s));
}
}
}
"level" -> true "noon" -> true "" -> true "a" -> true "Madam" -> false "abca" -> false
Time complexity: O(n) · Space complexity: O(n).
Approach 3: Recursion
It mirrors the definition directly, which interviewers like to see, but the call stack grows with the length of the string.
public class PalindromeRecursion {
static boolean isPalindrome(String s) {
if (s == null) {
return false;
}
return check(s, 0, s.length() - 1);
}
// The string is a palindrome if its outer characters match
// and the part between them is also a palindrome
private static boolean check(String s, int left, int right) {
if (left >= right) {
return true; // zero or one character left
}
if (s.charAt(left) != s.charAt(right)) {
return false;
}
return check(s, left + 1, right - 1);
}
public static void main(String[] args) {
String[] inputs = {"level", "noon", "", "a", "Madam", "abca"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + isPalindrome(s));
}
}
}
"level" -> true "noon" -> true "" -> true "a" -> true "Madam" -> false "abca" -> false
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Two Pointers | O(n) | O(1) |
| Reverse and Compare | O(n) | O(n) |
| Recursion | O(n) | O(n) |
Here n is the length of the string. Every approach compares at most n / 2 pairs. Two pointers uses constant extra space, while the reversed copy and the recursion stack both grow with n.
Interview Tips and Recommended Approach
- Clarify the rules first. Ask whether case, spaces and punctuation matter;
"Madam"isfalseunder an exact comparison. - Know the sentence follow-up. To ignore case and punctuation, skip characters that fail
Character.isLetterOrDigit()and compare withCharacter.toLowerCase(). - Get the loop condition right.
left < righthandles both odd and even lengths, and the empty string returnstruewithout entering the loop. - Do not reach for a stack, HashMap or sorting. A stack just rebuilds the reverse, counting answers a different question (can it be rearranged?), and sorting destroys the order.
Recommended Approach: Two Pointers
Why: it stops at the first mismatch, uses constant extra space and has no recursion depth limit. It is also the basis for many follow-up questions, such as palindromes that ignore punctuation.