In this chapter of the series, we will tackle a problem together using Dynamic Programming. The problem we are solving, courtesy of LeetCode, is as follows:

“Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1: Input: ‘babad’ Output: ‘bab’ Note: ‘aba’ is also a valid answer.

Example 2: Input: ‘cbbd’ Output: ‘bb’”

Recalling the first chapter of this series, do you think we should use a top-down or a bottom-up approach of DP to solve this problem? Take a moment to think of which approach you would use and why.

## My Approach and Why

Whenever I see a problem that looks solvable using DP, I can’t help but to first look at the brute-force solution. The brute-force solution is obviously very inefficient. It involves going through all the possible starting and ending positions for a substring and then checking if it is a palindrome. If we look at Example 1’s input (“babad”), using zero-indexing this gives us (0, 0), (0, 1), (0, 2), … , (0, n-1) as possible starting and ending positions for the first letter, (1, 1), (1, 2), … , (1, n-1) for the second letter, and so on, where n is the length of the string input (so in this case n = 5). This means a total of n + (n-1) + … + 1 = n(n+1)/2 different possible substrings for the string “babad,” and because verifying each substring would take O(n) time, the total time complexity amounts to O(n³).

So what did I take away from this brute-force analysis? We need to verify each and every substring possible. This means a bottom-up approach would work best.

Now that we have chosen which approach we will be using, let’s establish some base cases.

• Case 0 (n = 0): It is vacuously true that an empty string is a palindrome.
• Case 1 (n = 1): Since a letter by itself is a palindrome, all substrings of length 1 are a palindrome.
• Case 2 (n = 2): Substrings of length 2 can only be a palindrome if the first and last letters are the same.
• Case 3 (n = 3): Substrings of length 3 are palindromes if the first and last letters are the same. The middle letter doesn’t matter because we know that a single letter by itself is a palindrome. Hmm… this seems familiar. It seems like we can determine Case 3 by using the results of Case 1 and Case 2.
• Case 4 (n = 4): Substrings of length 4 are palindromes if the first and last letters are the same and the two remaining letters make up a palindrome.

By now, you should begin to see some structure in what makes up a palindrome. It seems like for words to be palindromes, the first and last letters have to be the same and the string excluding the first and last letters must also be a palindrome.

#data-science #interview #programming #python #devops

18.70 GEEK