Taro Logo

Palindromic Substrings

#18 Most AskedMedium
0 views
Topics:
StringsDynamic Programming

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 <= 1000
  • s consists of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What is the maximum length of the input string `s`?
  2. What character set does the string `s` contain? Are we restricted to lowercase English letters, or can it include uppercase letters, digits, and special/Unicode characters?
  3. How should we handle an empty string or a null input—should it return 0?
  4. Since the problem states that substrings with identical characters but different indices are counted separately, does a string like "aaa" contain 6 palindromic substrings (three "a", two "aa", one "aaa")?
  5. Is case sensitivity enforced, meaning 'A' and 'a' should be treated as distinct characters?

Brute Force Solution

Approach

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:

  1. Begin by looking at the very first letter of the text and treat it as a tiny standalone piece, counting it as a match since a single letter always reads the same both ways.
  2. Next, expand your view to include the next letter, making a two-letter piece, and check if it reads the same forwards and backwards.
  3. Continue expanding your view letter by letter to check every possible group of letters that starts at that very first position.
  4. Once you have checked all possible pieces starting at the first position, move your starting point to the second letter and repeat the entire process of growing and checking every possible piece.
  5. Keep shifting your starting point further down the text one letter at a time, and for each new starting point, check every possible ending point to examine every conceivable piece.
  6. Keep a running count every time you examine a piece and confirm that it reads the exact same forwards and backwards.
  7. Finally, once you have exhaustively checked every single possible piece from the first to the very last, report the total count of how many matching pieces you found.

Code Implementation

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_count

Big(O) Analysis

Time Complexity
O(n²) – The input size n represents the length of the string. The algorithm uses nested steps where the outer step shifts the starting point through all n characters, and the inner step expands outward to check every possible ending point for substrings. Checking all combinations of starting and ending positions yields approximately n * (n + 1) / 2 total substring examinations. Dropping the constants and lower-order terms, this quadratic growth simplifies to a Big O time complexity of O(n²).
Space Complexity
O(1) – The algorithm only maintains a running count and a few scalar integer variables to track the starting and ending points for the substrings being examined. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during the checks. Consequently, the extra memory required remains entirely constant regardless of the input string length N.

Optimal Solution

Approach

Instead 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:

  1. Imagine moving through the text and treating each position as a potential middle of a palindrome.
  2. First, consider odd-length palindromes by treating each single letter as a core center and looking to its immediate left and right neighbors.
  3. If the neighboring letters match, a palindrome is formed, so count it and continue looking further outward in both directions until the letters no longer match.
  4. Next, consider even-length palindromes by treating the space between any two adjacent letters as a core center.
  5. Look outward from this dual-letter center to the left and right, counting every expanding match until the symmetry breaks.
  6. Repeat this process for every possible center point across the entire text, making sure to count every successful outward expansion.
  7. By checking every single character and space as a potential center, you guarantee that no valid palindromic piece is missed while avoiding redundant checks.

Code Implementation

Big(O) Analysis

Time Complexity
O(n²) – We iterate through each of the n characters in the string, treating each position as a potential center for palindromes. For every character, the expand-around-center step checks outward in both directions, which can take up to n steps in the worst-case scenario. Since we perform this linear-time expansion for each of the n possible centers, the total operations scale roughly as n * n/2. Simplifying this quadratic growth results in a final time complexity of O(n²).
Space Complexity
O(1) – The algorithm relies entirely on a few primitive integer variables to track the current center indices, expansion boundaries, and the running total count of palindromic substrings. Because these pointers and counters consume a constant amount of memory regardless of the input string length, no auxiliary data structures grow with the input size N. Therefore, the extra memory used beyond the input itself remains strictly constant.

Edge Cases

Empty string input
How to Handle:
Return zero immediately as no palindromic substrings can exist.
Single character string
How to Handle:
Return one because a single character is trivially a palindrome.
String with all identical characters
How to Handle:
The expansion or dynamic programming approach correctly counts every possible substring combination using n times n plus one over two.
String of alternating characters
How to Handle:
Both odd and even length palindromes are correctly identified by expanding around every center.
Maximum length constraints
How to Handle:
An o of n squared expand-around-center approach runs efficiently within time limits without exceeding memory.
Strings with special characters or spaces
How to Handle:
Treat every character uniformly as part of the contiguous sequence without filtering.
0/37 completed