Introduction
The Palindrome String problem involves checking whether a string reads the same forward and backward.
Given a string s, the task is to determine:
- whether the string is a palindrome
- and return true or false
A palindrome remains unchanged after reversal.
This problem helps in understanding:
- string traversal
- comparison logic
- Two Pointer Technique
- symmetry checking
Example
Input:s = "madam"
Output:
True
Explanation:
Forward:
madam
Backward:
madam
Both are same.
Input:
s = "hello"
Output:
False
Explanation:
Forward:
hello
Backward:
olleh
Both are different.
Constraints
1 <= s.length <= 10^5s contains lowercase English letters
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Reverse the string
- Compare reversed string with original string
If both are equal:
- string is palindrome
Otherwise:
- not palindrome
Steps
- Reverse the string.
- Compare reversed string with original.
- If equal:
- return true
- Otherwise:
- return false
Dry Run
Input:s = "madam"
Reverse string:
"madam"
Compare:
madam == madam
Condition true
Final Result:
True
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
String reversal and comparison are performed.
Space Complexity: O(n)
Explanation:
Extra reversed string is used.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
The optimized solution uses the Two Pointer Technique.
The idea is:
- Place:
- left pointer at beginning
- right pointer at end
- Compare characters.
- If characters differ:
- not palindrome
- Otherwise:
- move pointers inward
This avoids creating an extra reversed string.
Steps
- Initialize:
- left = 0
- right = n - 1
- Compare characters.
- If mismatch found:
- return false
- Move pointers inward.
- Return true if traversal completes.
Dry Run
Input:s = "madam"
Initially:
left = 0 → m
right = 4 → m
Characters match
Move pointers left = 1 → a
right = 3 → a
Characters match
Move pointers
left = 2 → d
right = 2 → d
Traversal completed
Final Result:
True
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each character is checked once.
Space Complexity: O(1)
Explanation: No extra data structures are used.