Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000s consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a string of text and want to find every single piece inside it that reads the same forwards and backwards. The brute force approach involves looking at every possible slice of the text and testing each one to see if it qualifies.
Here's how the algorithm would work step-by-step:
def count_substrings(input_string):
total_palindrome_count = 0
string_length = len(input_string)
# Iterate through every possible starting position for our substring
for start_index in range(string_length):
# Iterate through every possible ending position for the current start position
for end_index in range(start_index, string_length):
current_substring = input_string[start_index:end_index + 1]
# Compare the slice to its reverse to confirm if it reads the same both ways
if current_substring == current_substring[::-1]:
total_palindrome_count += 1
return total_palindrome_countInstead of checking every single possible piece of text from the beginning to the end, the optimal approach looks outward from every potential center point to find palindromes. This clever shortcut lets us grow palindromes outward one character at a time, catching every valid match efficiently without wasted effort.
Here's how the algorithm would work step-by-step:
| Case | How to Handle |
|---|---|
| Empty string input | Return zero immediately as no palindromic substrings can exist. |
| Single character string | Return one because a single character is trivially a palindrome. |
| String with all identical characters | The expansion or dynamic programming approach correctly counts every possible substring combination using n times n plus one over two. |
| String of alternating characters | Both odd and even length palindromes are correctly identified by expanding around every center. |
| Maximum length constraints | An o of n squared expand-around-center approach runs efficiently within time limits without exceeding memory. |
| Strings with special characters or spaces | Treat every character uniformly as part of the contiguous sequence without filtering. |