10. Palindrome SubStrings
β GFG solution to the Palindrome SubStrings problem: count all palindromic substrings of length β₯ 2 using efficient center expansion technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a string s. Your task is to count all palindromic sub-strings present in the string where the length of the palindromic sub-string must be greater than or equal to 2.
A substring is palindromic if it reads the same forwards and backwards. The goal is to efficiently count all such valid palindromic substrings.
π Examples
Example 1
Input: s = "abaab"
Output: 3
Explanation: All palindromic substrings (of length > 1) are: "aba", "aa", "baab".Example 2
Input: s = "aaa"
Output: 3
Explanation: All palindromic substrings (of length > 1) are: "aa", "aa", "aaa".Example 3
π Constraints
$2 \le s.size() \le 5 \times 10^3$
$s$ contains only lowercase english characters
β
My Approach
The optimal approach uses the Center Expansion technique to efficiently find all palindromic substrings:
Center Expansion Technique
Core Idea:
For each possible center position, expand outwards to find all palindromes.
Handle both odd-length (single center) and even-length (two adjacent centers) palindromes.
Algorithm Steps:
For each index
ifrom 0 to n-1:Odd-length palindromes: Expand around center
iwith left=i-1, right=i+1Even-length palindromes: Expand around centers
iandi+1with left=i, right=i+1
Continue expansion while characters match and boundaries are valid.
Count each valid palindrome found during expansion.
Expansion Process:
Start from potential center(s) and expand outwards.
While
left >= 0,right < n, ands[left] == s[right]:Increment count (valid palindrome found).
Move
left--andright++to check longer palindromes.
Why This Works:
Every palindrome has a center (either single character or between two characters).
By checking all possible centers, we capture all palindromes.
Expansion ensures we find palindromes of all lengths from each center.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΒ²), where n is the length of the string. In the worst case (all characters same), each center can expand to create O(n) palindromes, and we have O(n) centers.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables like pointers and counters, regardless of input size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated