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