Learn two easy ways to test a Palindrome String: a clean recursive method and a space saving two-pointer loop. Includes code with comments, step-by-step explanation, dry run, and Big-O analysis.
The [Problem Link] is given here for your quick reference.
Contents:
[show]
What does the problem ask?
Given a string s
, tell whether it reads the same forwards and backwards.
Return True
if it is a palindrome, or False
otherwise.
Examples
Input | Output | Reason |
---|---|---|
"abba" | True | Same letters from both ends. |
"racecar" | True | Reads the same both ways. |
"abc" | False | a ≠ c . |
"a" | True | One letter is always a palindrome. |
Intuition & Approach
Key idea for both methods
Compare matching characters from the left and right ends and move inwards:
- If every pair matches → palindrome.
- If any pair differs → not a palindrome.
We show two ways to do this:
- Recursive – a clean self-calling check.
- Iterative (two pointers) – a simple
while
loop.
Code 1 – Recursive
class Solution:
# helper that checks s[left .. right]
def solve(self, s, left, right):
if left >= right: # crossed over → all pairs matched
return True
if s[left] != s[right]: # mismatch
return False
# move both pointers inward
return self.solve(s, left + 1, right - 1)
def isPalindrome(self, s: str) -> bool:
# check the whole string
return self.solve(s, 0, len(s) - 1)
Code 2 – Iterative Two Pointers
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
left = 0
right = n - 1
while left < right:
if s[left] != s[right]: # mismatch
return False
left += 1 # move inward
right -= 1
return True # all pairs matched
Code Walkthrough
Recursive method
- Base cases
left >= right
→ checked all pairs → returnTrue
.- Characters differ → return
False
.
- Recursive step
Moveleft
rightward andright
leftward and call again.
Iterative method
- Set two pointers:
left
at start,right
at end. - While they have not crossed:
- If characters differ → not a palindrome.
- Else move both pointers inward.
- Loop ends without a mismatch → palindrome.
Dry Run (iterative method on "abba"
)
left | right | s[left] | s[right] | Action |
---|---|---|---|---|
0 | 3 | a | a | match → move inward |
1 | 2 | b | b | match → move inward |
2 | 1 | – | – | pointers crossed → stop |
Return | True |
Complexity
Method | Time | Space |
---|---|---|
Recursive | O(n) | O(n) – call stack can be n/2 deep |
Iterative | O(n) | O(1) – only pointers |
n
is the length of the string.
Conclusion
A palindrome check needs only a linear scan from both ends.
- The recursive version is short and clear but uses extra stack space.
- The iterative two-pointer version saves space and is often preferred in practice.
Choose the one that best fits your style or memory limits.
For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.