Search⌘ K
AI Features

Solution: Palindromic Substrings

Explore how to use dynamic programming to count all palindromic substrings in a given string. Learn to optimize naive methods by storing results in a lookup table, reducing time complexity from cubic to quadratic while handling substrings of different lengths systematically.

Statement

Given a string, s, return the number of palindromic substrings contained in it. A substring is a contiguous sequence of characters in a string. A palindrome is a phrase, word, or sequence that reads the same forward and backward.

Constraints:

  • 11 \leq s.Length 1000\leq 1000

  • s consists of only lowercase English characters.

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which to follow based on considerations such as time complexity and implementation constraints.

Naive approach

A naive approach to this problem is to find all possible substrings and count the number of palindromic substrings. For example, consider the string “deed”. The number of substrings contained in “deed” is 10: “d”, “e”, “e”, “d”, “de”, “ee”, “ed”, “dee”, “eed”, and “deed”. Out of these 10 substrings, six are palindromes: “d”, “e”, “e”, “d”, “ee”, and “deed”. Therefore, the number of palindromic substrings in “deed” is six.

We get the required result, but at what cost? Since we’re checking every possible substring, the total number of substrings in a string of length nn is O(n2)O(n^2) ...