1. Brute Force Substring Checking
Intuition
Iterate all start indices i from 0 to n - 1 and all end indices j from i to n - 1. For each substring s[i...j], check if it is a palindrome. If true, increment count.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
count = 0. - Loop
ifrom 0 ton - 1: - Loop
jfromiton - 1: - If
isPalindrome(s, i, j):count++. - Return
count.
Brute Force Substring Checking
2 of 2 questions left todayObservation: Total substrings in string of length 3 is $N(N+1)/2 = 6$
Observation: Total substrings in string of length 3 is N(N+1)/2 = 6.
Decision: All 3 single-letter substrings are palindromic. Increment count by 3.
Invariant: Every single character trivially equals its reverse.
#include <iostream>#include <string> class Solution { bool isPalindrome(const std::string& s, int l, int r) { while (l < r) { if (s[l++] != s[r--]) return false; } return true; }public: int countSubstrings(std::string s) { int n = s.size(), count = 0; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { if (isPalindrome(s, i, j)) { count++; } } } return count; }}; int main() { Solution sol; std::cout << sol.countSubstrings("abc") << std::endl; // 3 std::cout << sol.countSubstrings("aaa") << std::endl; // 6 return 0;}Time & Space Complexity
- Time complexity:
O(N^3)— N * (N + 1) / 2 substrings, each taking O(N) to check. - Space complexity:
O(1) extra space
Why Brute Force Doesn't Scale:
Expanding around centers achieves optimal O(N2) time and O(1) space.
Operates purely with integer index pointers with zero auxiliary memory allocations.