๐
Date: Jan 28, 2026
๐ฅ Topic: Logic Building: Palindrome Check
๐ค What is a Palindrome?
A palindrome is a word, number, or phrase that reads the same backwards as forwards.
- Valid: MOM, RACECAR, MADAM, 121
- Invalid: HELLO, 123
๐ก The Two-Pointer Approach
Instead of reversing the whole string (which uses extra memory), I used the Two-Pointer Technique.
- Put one finger (pointer) at the Start.
- Put one finger at the End.
- Compare them. If they match, move start forward and end backward.
- If they don't match at any point -> Not a Palindrome.
๐ป Day 28 Code
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout << "Enter string: ";
cin >> s;
int start = 0;
int end = s.length() - 1;
bool isPalindrome = true;
while(start < end) {
if(s[start] != s[end]) {
isPalindrome = false;
break; // Stop checking
}
start++;
end--;
}
if(isPalindrome)
cout << "Yes! It is a Palindrome." << endl;
else
cout << "No. Not a Palindrome." << endl;
return 0;
}
๐ญ Thoughts
This logic is O(n/2), which is O(n) Time Complexity. It's efficient. The two-pointer pattern is something I'll definitely see again in DSA.
No comments:
Post a Comment