Count Palindromic Substrings in Python



In Python, finding palindromic substrings (sequences that read the same forwards and backwards) can be done using various methods, such as expanding from the centre and the brute force method etc.

Some of the common approaches to finding palindromic substrings in Python are as follows:

  • Expand around the centre: It involves taking each character in the word as the centre of the potential palindrome.

  • Brute force: This method will check every possible substring of the word and verify if it's a palindrome.

  • Dynamic Programming: To find the number of palindromic substrings by creating 2D tables.

Expand Around Center Approach

This method checks each character in the string as a possible centre of a palindrome. Each character can be the centre for odd-length palindromes, and pairs of adjacent characters can be the centres for even-length palindromes.

The approach involves expanding outwards from these centres as long as the characters on both sides are equal. It counts how many palindromic substrings can be found this way.

Example

In the following example, for the string "banana," each character is treated as a centre for potential palindromes. By expanding around these centres, the method identifies substrings like 'a', 'ana', and 'anana,' resulting in a total of 10 palindromic substrings.

def expand_around_center(s: str) -> int:
    n = len(s)
    count = 0
    
    def expand(left: int, right: int):
        nonlocal count
        while left >= 0 and right < n and s[left] == s[right]:
            count += 1
            left -= 1
            right += 1

    for i in range(n):
        # Odd-length palindromes
        expand(i, i)
        # Even-length palindromes
        expand(i, i + 1)
    
    return count

# Example usage:
my_string = "banana"
print(f"Number of palindromic substrings: {expand_around_center(s)}")

Output

Number of palindromic substrings: 10

Brute Force Approach

This method examines every possible substring of the string to check if it is a palindrome. A separate check is performed to determine if a given substring reads the same forwards and backwards. During the process, all identified palindromic substrings are collected in a list.

Example

In this example, the string "repaper" is examined by generating all possible substrings and checking each one to see if it is a palindrome. It recognizes palindromic substrings such as 'repaper', 'epape', and 'pap,' leading to a total of three palindromic substrings.

def is_palindrome(word):
# To Check if the given word is palindrome
    return word == word[::-1]

def find_palindromes_bruteforce(input_word):
    palindromes = []
    n = len(input_word)
    for i in range(n):
        for j in range(i + 1, n):
		
		# To Check if the substring is a palindrome	
            if is_palindrome(input_word[i:j+1]):
			
			 # Adding palindrome to the list
                palindromes.append(input_word[i:j+1])
    return palindromes

string = 'repaper'
palindromes = find_palindromes_bruteforce(string)
print ('Palindrome substrings of ',string,' are:\n',palindromes)

Output

Palindrome substrings of  repaper  are:
 ['repaper', 'epape', 'pap']

Dynamic Programming Approach

The dynamic programming method uses a two-dimensional table to track which substrings are palindromes. Each entry in the table indicates whether the substring defined by two indices is a palindrome. The algorithm first marks all single characters as palindromes, then checks larger substrings based on the characters at the ends, updating the table accordingly and counting the total number of palindromic substrings.

Example

In this example, for "radar" (input string) the approach uses a table to track palindromic substrings. It marks single characters as palindromes and checks pairs and larger substrings. Eventually, it identifies seven palindromic substrings, such as 'r', 'a', 'ada', and 'radar.'

def count_palindromic_substrings_dp(my_string: str) -> int:
    n = len(my_string)
	 # Creating a 2D DP table with False
    dp = [[False] * n for _ in range(n)]
    count = 0
    
    for i in range(n):
	# Single characters are palindromes	
        dp[i][i] = True
        count += 1
		
     # Considering substrings of length 2 or more
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
			
			# Checking if the ends match
            if my_string[i] == my_string[j]:
                if length == 2 or dp[i + 1][j - 1]:
                    dp[i][j] = True
                    count += 1

    return count


my_string = "radar"
print(f"Number of palindromic substrings: {count_palindromic_substrings_dp(my_string)}")

Output

Number of palindromic substrings: 7
Updated on: 2024-12-12T17:34:07+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements