1. Try Deleting Every Character
Intuition
First check if s is already a palindrome. If not, iterate i from 0 to N - 1, constructing t = s[0...i-1] + s[i+1...N-1]. Check if t is a palindrome. If any t is a palindrome, return true; else false.
When to apply: Basic baseline comparison.
Algorithm
- If
sis palindrome: return true. - For
ifrom 0 tos.length - 1: -
t = s.substr(0, i) + s.substr(i + 1). - If
tis palindrome: return true. - Return false.
Exhaustive Deletion Testing Trace
2 of 2 questions left todayObservation: Test deleting character at index 0 ('a')
Observation: Test deleting character at index 0 ('a'). Substring is "bca".
Decision: "bca" !== "acb". Deleting index 0 does not yield a palindrome.
Invariant: Candidate 0 rejected.
#include <iostream>#include <string> class Solution { bool isPal(const std::string& s) { int l = 0, r = s.size() - 1; while (l < r) { if (s[l++] != s[r--]) return false; } return true; }public: bool validPalindrome(std::string s) { if (isPal(s)) return true; int n = s.size(); for (int i = 0; i < n; ++i) { std::string t = s.substr(0, i) + s.substr(i + 1); if (isPal(t)) return true; } return false; }}; int main() { Solution sol; std::cout << (sol.validPalindrome("abca") ? "true" : "false") << std::endl; // true std::cout << (sol.validPalindrome("abc") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— N iterations, each performing an O(N) string creation and palindrome check. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
Reduces search tree from O(N) possibilities to exactly two deterministic sub-scans.
Passes indices (l, r) to avoid substring allocations.