Palindromic Substrings

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
109 upvotes
Asked in companies
SalesforceMicrosoftInfosys

Problem statement

You have been given a string STR. Your task is to find the total number of palindromic substrings of STR.

Example :
If the input string is "abbc", then all the possible palindromic substrings would be: ["a", "b", "b", c", "bb"] and hence, the output will be 5 since we have 5 substrings in total which form a palindrome.
Note :
A string is said to be a 'Palindrome' if it is read the same forwards and backwards. 
For example, “abba” is a palindrome, but “abbc” is not.

A 'Substring' is a contiguous sequence of characters within a string. 
For example, "a", "b", "c", "ab", "bc", "abc" are substrings of "abc".
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first and only line of each test case contains the string STR for which you have to count the number of palindromic substrings.
Output Format :
For each test case, return the total number of palindromic substrings possible.

Output for each test case will be printed in a separate line.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
Constraints :
1 <= t <= 100
0 <= N <= 1000

Where 't' is the number of test cases, 'N' is the length of the given string.
Time Limit: 1 sec.
Sample Input 1 :
1
abc
Sample Output 1 :
3
Explanation For Sample Output 1:
All the substrings of the given string are "a", "b", "c", "ab", "bc", "abc".
The plaindromics substrings are "a", "b", "c". So the output will be 3.   
Sample Input 2 :
1
aaa
Sample Output 2 :
6
Hint

Think you have access to all the substrings of the given string in a storage. From the pool of all the possible substrings, which all are palindromes?

Approaches (5)
Brute Force Approach
  1. Initialize a count variable with 0 to keep track of the number of palindromic substrings.
  2. Let n be the length of the input string. Run a double nested loop. The outer loop will go from i = 0 to i = n - 1, and the inner loop will go from j = i to j = n - 1. i and j denote the start and end indices of a substring in the input string.
  3. Check whether the substring from index i to j forms a palindrome.
    • If it does, increase the count by 1 and move to the next iteration.
    • If it doesn't, move to the next iteration.
  4. Return the count.
Time Complexity

O(N^3), where N is the length of the string.

 

1. Iterating over the start and endpoints, all the substrings will take O(N^2) time.

2. Iterating over one substring will take O(N) time.

Hence, the total time taken would be O(N * N^2) => O(N^3).

Space Complexity

O(1).

 

Constant space is used.

Code Solution
(100% EXP penalty)
Palindromic Substrings
Full screen
Console