C++ Program to Check Palindrome String
for or while and returns true if all pairs match; for example, bool isPalindrome(string s) { int n = s.size(); for (int i = 0; i < n / 2; i++) if (s[i] != s[n - i - 1]) return false; return true; }.Examples
How to Think About It
Algorithm
Code
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s) {
int n = s.size();
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - i - 1])
return false;
}
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str))
cout << str << " is a palindrome" << endl;
else
cout << str << " is not a palindrome" << endl;
return 0;
}Dry Run
Let's trace the string 'madam' through the code
Input string
str = 'madam'
Calculate length
n = 5
Compare characters
Compare s[0] = 'm' and s[4] = 'm' -> match Compare s[1] = 'a' and s[3] = 'a' -> match Loop ends as i < n/2 (i < 2)
Result
All pairs matched, return true
| i | s[i] | s[n-i-1] | Match? |
|---|---|---|---|
| 0 | m | m | Yes |
| 1 | a | a | Yes |
Why This Works
Step 1: Check pairs from ends
The code compares characters from the start and end moving inward using for loop.
Step 2: Return false on mismatch
If any pair of characters differ, the function returns false immediately.
Step 3: Return true if all match
If the loop finishes without mismatches, the string is a palindrome, so it returns true.
Alternative Approaches
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s) {
int left = 0, right = s.size() - 1;
while (left < right) {
if (s[left] != s[right])
return false;
left++;
right--;
}
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
cout << str << (isPalindrome(str) ? " is a palindrome" : " is not a palindrome") << endl;
return 0;
}#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string str, rev; cout << "Enter a string: "; cin >> str; rev = str; reverse(rev.begin(), rev.end()); if (str == rev) cout << str << " is a palindrome" << endl; else cout << str << " is not a palindrome" << endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks up to half the string length, so it runs in linear time O(n), where n is the string length.
Space Complexity
It uses constant extra space O(1) because it only stores a few variables and does comparisons in place.
Which Approach is Fastest?
The two-pointer and loop comparison methods are fastest with O(1) space, while reversing the string uses extra space and may be slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop comparison | O(n) | O(1) | Memory efficient, fast |
| Two pointers | O(n) | O(1) | Clear logic, efficient |
| String reverse | O(n) | O(n) | Simple code, uses extra space |