Palindromic Substrings
Palindromic Substrings
Section titled “Palindromic Substrings”
Medium
Day 12 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given a string s, return the number of palindromic substrings in it.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
s = "abc" - Output:
3 - Explanation: Three palindromic strings: “a”, “b”, “c”.
Example 2:
- Input:
s = "aaa" - Output:
6
Constraints:
1 <= s.length <= 1000
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Expand around center and count every valid expansion.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Expand Around Center Counting
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Problem["Problem of Size N"] --> Sub["Break into Subproblems DP[i]"] Sub --> Base["Base Cases: DP[0], DP[1]"] Base --> Trans["State Transition: DP[i] = f(DP[i-1], DP[i-2], ...)"] Trans --> Table["Fill DP Table / Variables"] Table --> Result["Return DP[N]"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function countSubstrings(s) { let count = 0; function expand(l, r) { while (l >= 0 && r < s.length && s[l] === s[r]) { count++; l--; r++; } } for (let i = 0; i < s.length; i++) { expand(i, i); expand(i, i + 1); } return count;}- Time Complexity:
O(n^2) - Space Complexity:
O(1) - Explanation: Center expansion counting.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function countSubstrings(s) { let count = 0; function expand(l, r) { while (l >= 0 && r < s.length && s[l] === s[r]) { count++; l--; r++; } } for (let i = 0; i < s.length; i++) { expand(i, i); expand(i, i + 1); } return count;}- Time Complexity:
O(n^2) - Space Complexity:
O(1) - Explanation: O(n^2) time center expansion.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”Increment total count every time s[l] === s[r] during outwards expansion.
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Count expansions from single and double centers.