Quick revision
The short answer
Checking whether a string is a palindrome is a two pointer problem on a string. We put one index at the start and one at the end, compare the two characters, and move both inward until they meet; the first unequal pair means it is not a palindrome. That is O(n) time and O(1) extra space, and a phrase version skips anything that is not a letter or digit and ignores case.
The solution
What it costs
| Approach | Time | Extra space | Stops at first mismatch? |
|---|---|---|---|
| Reverse and compare (brute force) | O(n) | O(n) | no, copies everything first |
| Two pointers from both ends | O(n) | O(1) | yes |
What to remember
We checked a palindrome by keeping two indexes, one at each end, comparing each mirror pair and moving inward until the fingers meet or a pair differs, in O(n) time and O(1) extra space, and we extended it to sentences by skipping characters that are not letters or digits and comparing in lower case. The clue to remember is a question that compares the two ends of something and lets each finished pair be forgotten: put a pointer at each end and walk them towards the middle, the way a strip of paper folds onto itself.
1What it means for a string to read the same both ways
Take a strip of paper and write the word racecar along it in big letters, one letter per square. Now fold the strip exactly in half. The first r lands on the last r, the a beside it lands on the other a, the c lands on the c, and the e in the middle lands on the fold. Every letter lands on an equal letter. A string that behaves like this, reading the same from the front and from the back, is called a palindrome.
Let us say the same thing with positions, because the code will need them. Java numbers the characters of a string from 0, so racecar has positions 0 to 6. When we fold, position 0 meets position 6, position 1 meets position 5, and position 2 meets position 4. Position 3 meets itself. In general, for a string of length n, position i meets position n - 1 - i, its mirror partner. A string is a palindrome when every character equals its mirror partner.
Now try a word that fails, abca. It has four characters, positions 0 to 3. Position 0, a, meets position 3, a, which is fine. Position 1, b, meets position 2, c, and they differ. One unequal pair is enough, so abca is not a palindrome. Notice that we did not need to look at anything else once we found that pair.
Boxes with the same marking are mirror partners: 0 with 6, 1 with 5, 2 with 4. The middle box, 3, is its own partner.
- pairs to check
- (0,6) (1,5) (2,4)
- middle
- index 3, needs no partner
- expected
- true
1Fold racecar in the middle and each letter lands on its partner: r on r, a on a, c on c. The middle e lands on itself, so racecar is a palindrome.
What to assume
- Does case matter, and do spaces and punctuation count?
- In the exact check every character counts and R differs from r. A second check, for phrases, ignores everything except letters and digits and ignores case, so that A man, a plan, a canal, Panama comes out true.
- Can the string be empty?
- An empty string has no unequal pair, so we treat it as a palindrome.
The question is short, so a careful candidate asks a few things first. Does case matter, so that Racecar with a capital R fails? Do spaces and punctuation count? Can the string be empty? We will write an exact check first, where every character counts and R differs from r, and then a phrase check that ignores everything except letters and digits and ignores case, so that sentences such as A man, a plan, a canal, Panama come out true. An empty string has no unequal pair, so we treat it as a palindrome.
If you are a little nervous, this problem is smaller than it looks. There is no clever data structure to learn; we are only teaching two fingers to walk towards each other along a word.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise the two pointer pattern in this question
Many of us, reading the question for the first time, think of the obvious meaning of the words. Reads the same backward sounds like turn it backward and compare, so we reach for a way to reverse the string. That is a sensible thought, and it is the brute force we will write next. But let us read the question more slowly and look for clues about how the work is really shaped.
The first clue is the phrase forward and backward. It tells us two directions are involved at once, one from each end. The definition we wrote, position i against position n - 1 - i, pairs the first character with the last, the second with the second last, and so on. Each pair has one member near the front and one near the back.
The second clue is how the pairs move. When we finish one pair, the next pair is one step inward on both sides. So if we keep one index at the front and one at the back, both only ever move towards the middle, and they meet once every pair is checked. Nothing needs to be stored, because each pair is checked once and never needed again.
These clues point to the two pointers pattern. A pointer here is simply an index into the string, like a finger resting on one letter, and two pointers means two such fingers moving by a rule. The question sits in the strings and tries family, but two pointers is the technique that solves it. The general rule to carry away is this. When a problem compares or combines elements from both ends of an array or string, and every step can discard the outer pair for good, start a pointer at each end and move them inward.
Some patterns look similar but do not fit. A sliding window also uses two indexes, but both move in the same direction to mark a stretch of the string, while ours move towards each other. A trie, a tree that stores many words by their shared beginnings, helps when we test many words against a dictionary, as in the palindrome pairs problem, but not for one string. And a stack could reverse the string for us, but that is the brute force again in different clothes.
3The honest first attempt, reversing the string and comparing
The brute force follows the words of the question exactly: build the reversed string and check whether it equals the original. In Java that is one line with StringBuilder, a class that holds characters we can change, including reversing them. It is correct, and in a real program it is often perfectly fine, so it is a good answer to mention first.
Let us count the work on abca by hand. First StringBuilder copies all four characters, a, b, c, a. Then reverse swaps them into a, c, b, a. Then toString copies them again into a new String. Only then does equals compare, finding a equal to a and b different from c, and returning false. So we did about twelve character steps and built two new objects to answer a question that the second pair settled.
For a string of n characters the copying alone is about 3n steps, so the time is O(n), read as order n, meaning it grows in step with n. The extra memory, called the space, is also O(n), because the reversed copy is as long as the string. Neither of these is a disaster. But think of a string of a million characters whose first and last characters differ. The brute force still copies and reverses all million before it notices. That is where it repeats work for nothing: everything after the first unequal pair, and the whole copy, were never needed.
So let us ask the question that leads us further. When we compared the reversed copy with the original, what were we really comparing? Position 0 of the copy is position n - 1 of the original. So equals was checking each character against its mirror partner. We could do that directly, reading the partner from the original string, with no copy at all.
4Getting to two fingers moving inward
Put one finger on the first letter and another on the last. In code these are two int variables, left = 0 and right = n - 1. At each step we compare s.charAt(left) with s.charAt(right). If they differ, we have found an unequal mirror pair and can return false straight away. If they are equal, this pair is fine and we never need it again, so we move left one step forward and right one step back.
Now the question a beginner always asks. When do we stop? Let us try the two kinds of length. For racecar, length 7, the fingers go 0 and 6, 1 and 5, 2 and 4, and then both sit on 3, the middle e. A character compared with itself cannot be unequal, so we can stop as soon as left is no longer smaller than right. For abba, length 4, the fingers go 0 and 3, then 1 and 2, and after that left is 2 and right is 1; they have crossed. Again left < right is false. So one test, while left < right, handles both odd and even lengths.
Why is this correct? Every mirror pair (i, n - 1 - i) with i smaller than its partner is visited exactly once, in order from the outside in, because left and right are always partners: their sum stays n - 1 as one goes up and the other goes down. If all those pairs match, the string is a palindrome by definition. If one does not, it is not, and we return false at that very pair.
The phrase check adds one rule, and the picture below shows it on the short phrase Taco cat. Before comparing, if the character at left is not a letter or digit, we move left forward and go round the loop again without comparing anything. We do the same for right, moving it backward. Only when both fingers rest on letters or digits do we compare them, after turning both into lower case with Character.toLowerCase.
The empty box at index 4 is the space. The phrase check skips anything that is not a letter or digit and compares letters in lower case.
- left, right
- 0, 7
- compare
- t and t
- result
- match
1left is on T and right on t. Both are letters, and in lower case both are t, so they match and both pointers move inward.
- left, right
- 1, 6
- compare
- a and a
- result
- match
2left is on a at 1 and right on a at 6. They match, so the pointers move to 2 and 5.
- left, right
- 2, 5
- compare
- c and c
- result
- match
3c at 2 and c at 5 match too, so left moves to 3 and right to 4.
- left, right
- 3, 4
- right is on
- a space, skip it
4right is on the space at 4, which is not a letter or digit. We do not compare; we only move right back to 3 and go round the loop again.
- left, right
- 3, 3
- returns
- true
5Now left and right are both 3, so left < right is false and the loop ends. Every pair of letters matched, and we return true.
A tempting mistake in the phrase check is to skip with an inner while loop, such as while (!Character.isLetterOrDigit(s.charAt(left))) left++, without also checking left < right. On a string of only punctuation, such as two commas, that loop runs off the end and throws an exception. Moving one step and using continue lets the outer test, left < right, guard every step.
5Watching the two pointers on racecar and abca
The picture runs the exact check twice, first on racecar, a palindrome of odd length, and then on abca, which fails. The labels left and right sit under the two characters being compared, and the panel shows the pair and what the comparison decided.
Watch how the finished pairs grow from the outside in, and watch where each run stops: racecar stops when the fingers meet, and abca stops at the first unequal pair.
left and right start at the two ends and step inward together. Compared boxes are the pair being checked now; finished boxes are pairs already found equal.
- string
- racecar
- left, right
- 0, 6
1racecar has 7 characters, so left starts at 0 and right at 6. The loop will run while left < right.
- left, right
- 0, 6
- compare
- r and r
- result
- match, move in
2We compare
charAt(0), r, withcharAt(6), r. They are equal, so this pair cannot break the palindrome, and left moves to 1, right to 5.- left, right
- 1, 5
- compare
- a and a
- result
- match, move in
3a at 1 and a at 5 match. The outer pair is finished, and the pointers step inward again to 2 and 4.
- left, right
- 2, 4
- compare
- c and c
- result
- match, move in
4c at 2 and c at 4 match. left becomes 3 and right becomes 3, both on the middle e.
- left, right
- 3, 3
- comparisons
- 3
- returns
- true
5left equals right, so left < right is false and the loop stops. The middle e has no partner and cannot break anything. We return true after three comparisons.
- string
- abca
- left, right
- 0, 3
6Now abca, 4 characters. left starts at 0 and right at 3. There is no middle character this time.
- left, right
- 0, 3
- compare
- a and a
- result
- match, move in
7a at 0 and a at 3 match, so the pointers move to 1 and 2.
- left, right
- 1, 2
- compare
- b and c
- returns
- false
8b at 1 and c at 2 differ. One broken pair is enough to prove abca is not a palindrome, so we return false at once.
Let us read the important frames back. In the first racecar frame nothing has been compared yet; left is 0 and right is 6. In the next three frames the pairs r and r, a and a, c and c each match, and the fingers step inward each time. In the fifth frame both fingers are on 3, the loop test fails, and we return true after only three comparisons, though the string has seven characters.
The abca frames show the early exit. The outer a and a match, the fingers move to 1 and 2, and b differs from c. We return false at once, without building anything or looking further. On a long string that fails near the ends, this is the saving over the brute force.
6The complete Java program
Here is the whole class with both checks. main tries an odd and an even palindrome, a near miss, the empty string, a difference only in case, and two classic sentences for the phrase check, and each comment shows what that line prints.
Let us read isPalindrome in the order it runs. left starts at 0 and right at s.length() - 1, the two ends. The while loop runs only while left < right, so there is always a real pair to compare. Inside, if s.charAt(left) != s.charAt(right), we return false at once. Otherwise left++ and right-- move both fingers inward. If the loop ends without returning, every pair matched, so we return true.
isPalindromePhrase has the same shape with two extra lines at the top of the loop. We read the two characters into a and b. If a is not a letter or digit, Character.isLetterOrDigit returns false, so we move left forward and continue, which jumps back to the loop test. The next line does the same for b and right. Only when both are letters or digits do we compare Character.toLowerCase(a) with Character.toLowerCase(b), so T and t count as equal.
Notice that the exact check prints false for Racecar, because R and r are different characters to Java, while the phrase check would say true. That difference is exactly what our clarifying question was about. One small detail is that Character.isLetterOrDigit also accepts letters from other alphabets, such as accented letters; if the interviewer wants plain English letters only, a range check on a to z, A to Z and 0 to 9 does that.
7How much it costs, and the cases at the edges
Let us count on the examples first. racecar took three comparisons, and abca took two. In general, each pass of the loop either returns or moves at least one finger towards the other, and the fingers start n - 1 apart, so the loop runs at most n times. Each pass does a fixed amount of work, so the time is O(n). We cannot do better in the worst case, because a palindrome has to have every pair checked.
The space is the real gain. We keep two ints and, in the phrase check, two chars, whether the string has seven characters or seven million, so the extra space is O(1), read as constant. The brute force needed a full reversed copy, O(n).
| Approach | Time | Extra space | Stops at first mismatch? |
|---|---|---|---|
| Reverse and compare (brute force) | O(n) | O(n) | no, copies everything first |
| Two pointers from both ends | O(n) | O(1) | yes |
The edge cases come out of the loop with no special code. For the empty string, right starts at -1, the test 0 < -1 is false, the loop never runs, and we return true. A single character has left = right = 0, so it is true at once. A string of only punctuation, such as ?!, makes the phrase check skip until the fingers meet and return true, because no two letters disagree. A null string would throw, so if null is possible we should ask what it should mean and check for it first.
One more edge case is worth naming because it surprises people. Some characters outside the basic range, such as many emoji, take two Java chars each. Reversing or mirroring by char can split them. For ordinary text this never matters, and saying so briefly shows care without overcomplicating the answer.
8Follow-up questions
How would you check whether a string can become a palindrome by deleting at most one character?
We run the same two pointer loop. While the pairs match, nothing changes. At the first unequal pair, at left and right, we have one deletion to spend, and it must remove one of those two characters, because every pair outside them already matched. So we check two smaller ranges with the plain loop: left + 1 to right, as if we deleted the left character, and left to right - 1, as if we deleted the right one. If either range is a palindrome, the answer is true. Each check is O(n), so the total is still O(n) time and O(1) space.
How do you check whether a number is a palindrome without turning it into a string?
We build the reverse of the number's second half with arithmetic. While the number is larger than the reversed half, we take its last digit with x % 10, add it to reversed as reversed = reversed * 10 + digit, and drop it with x = x / 10. For 1221 we end with x = 12 and reversed = 12, equal, so it is a palindrome. For an odd count of digits, such as 12321, we end with x = 12 and reversed = 123, so we compare x with reversed / 10. Negative numbers and numbers ending in 0, other than 0 itself, are never palindromes, so we return false for them first.
9Conclusion
We checked a palindrome by keeping two indexes, one at each end, comparing each mirror pair and moving inward until the fingers meet or a pair differs, in O(n) time and O(1) extra space, and we extended it to sentences by skipping characters that are not letters or digits and comparing in lower case. The clue to remember is a question that compares the two ends of something and lets each finished pair be forgotten: put a pointer at each end and walk them towards the middle, the way a strip of paper folds onto itself.
Open with
First I would confirm the rules: whether case matters, whether spaces and punctuation count, and that an empty string counts as a palindrome. The simplest approach reverses the string with a StringBuilder and compares, which is O(n) time but O(n) extra space, and it copies everything before finding even an early mismatch.
Then, if they want more
Instead I use two pointers. left starts at 0 and right at the last index. While left is less than right, I compare the two characters; if they differ, I return false immediately, otherwise I move left forward and right backward. When the pointers meet or cross, every mirror pair has matched, so I return true.
The loop test left < right handles both odd lengths, where the middle character needs no partner, and even lengths. That is O(n) time and O(1) space.
For phrases, I skip any character that is not a letter or digit by moving that pointer one step and continuing, so the loop test still guards every step, and I compare the two characters in lower case. An empty string or a single character returns true without entering the loop.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 31 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Determine whether a given string reads the same forward and backward.": https://scrivio-interview-library.netlify.app/data-structures/solutions/determine-whether-a-given-string-reads-the-same-forward-and-back-d52d9e/