Search⌘ K
AI Features

Solution: Palindromic Substrings

Explore how to identify and count palindromic substrings within a string by leveraging dynamic programming. Learn to create and use a lookup table to optimize checks, reducing time complexity from cubic to quadratic. This lesson helps you understand practical algorithm design for substring problems by building on foundational dynamic programming concepts.

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) ...