๐ Date: Jan 17, 2026
๐ง Mood: Mirror Mode ๐ช
๐ฅ Topic: DSA: Recursion with Strings (Reverse & Palindrome)
๐ค Strings & Recursion
How do you process a String using Recursion?
Think of it like a Two Pointer approach, but without a `while` loop.
- We process the corners (Start and End).
- Then we ask Recursion to handle the remaining inner part.
๐ 1. Reverse a String
Task: Convert "SAHIL" to "LIHAS".
Logic: Swap `s[start]` and `s[end]`. Then call function for `start+1` and `end-1`.
#include <iostream>
using namespace std;
// Pass by Reference (&str) so changes happen in original string
void reverse(string &str, int i, int j) {
// 1. BASE CASE (Stop when pointers cross)
if(i > j) {
return;
}
// 2. PROCESSING (Swap characters)
swap(str[i], str[j]);
// 3. RECURSIVE CALL (Move inside)
reverse(str, i+1, j-1);
}
int main() {
string name = "SAHIL";
reverse(name, 0, name.length()-1);
cout << "Reversed: " << name << endl;
return 0;
}
๐ช 2. Check Palindrome
A Palindrome reads the same forwards and backwards (e.g., "MAM", "RACECAR").
Logic:
1. Check if first and last chars are same.
2. If YES, ask recursion to check the inner string.
3. If NO, return False immediately.
#include <iostream>
using namespace std;
bool checkPalindrome(string &str, int i, int j) {
// 1. BASE CASE (If we cross middle, it's a Palindrome)
if(i >= j) {
return true;
}
// 2. CHECK (If corners don't match, fail immediately)
if(str[i] != str[j]) {
return false;
}
// 3. RECURSIVE CALL (Check remaining part)
return checkPalindrome(str, i+1, j-1);
}
int main() {
string s = "racecar";
bool isPal = checkPalindrome(s, 0, s.length()-1);
if(isPal) {
cout << "It is a Palindrome ✅";
} else {
cout << "Not a Palindrome ❌";
}
return 0;
}
๐ Day 54 Challenge
- Write a recursive function to check if a string is a Binary Palindrome (e.g., "1001" is True).
- Power Set (Subsequences): This is hard. Try to print all subsequences of string "abc" (Hint: Include/Exclude Pattern).
We will cover this in Day 55, but try researching it today!
Next Up: Day 55 - The Hardest Part: Recursion with Subsequences (Include/Exclude).
No comments:
Post a Comment