Wouldn't this solution be O(n^3) because s[l:r+1] could make a copy of s for each iteration? An improvement would be to store the indices in variables like res_l and res_r when there is a larger palindrome instead of storing the string itself in res. Then, outside of the loops, return s[res_l:res_r].
Good catch! you're exactly correct, and your proposed solution would be O(n^2). I hope the video still explains the main idea, but thank you for pointing this out. I will try to catch mistakes like this in the future.
Hey Devon Fulcher, Hii, if you don't mind can you please share your code, it would increase my knowledge in approaching these huge time complexity questions
@@shivakumart7269 Here you go leetcode.com/problems/longest-palindromic-substring/discuss/1187935/Storing-string-indices-vs.-using-substring! My small fix doesn't seem to make the runtime much faster in terms of ms but it is more correct in terms of algorithmic complexity.
Hi Devon, do you mind explaining why s[l:r + 1] would result in a O(N^3)? How does making a copy of s for each iteration make the solution worse? Thank you.
time complexity = O(|s|^2) spcae complexity = O(1) class Solution { private: string expandAroundCenter(string s, int left, int right) { int n = s.length(); while (left >= 0 && right < n && s[left] == s[right]) { left--; right++; } return s.substr(left + 1, right - left - 1); } public: string longestPalin (string S) { int n = S.length(); if (n < 2) { return S; } string longestPalindrome = S.substr(0, 1); // default to the first character for (int i = 0; i < n - 1; i++) { string palindromeOdd = expandAroundCenter(S, i, i); if (palindromeOdd.length() > longestPalindrome.length()) { longestPalindrome = palindromeOdd; } string palindromeEven = expandAroundCenter(S, i, i + 1); if (palindromeEven.length() > longestPalindrome.length()) { longestPalindrome = palindromeEven; } } return longestPalindrome; } };
Thanks (this isn’t a dynamic programming problem but it’s marked as dynamic programming on neetcode website) TODO:- take notes in onenote and implement Trick is to expand outward at each character (expanding to the left and right) to check for palindrome. BAB if you expand outward from A you will check that left and right pointers are equal, while they’re equal keep expanding. WE DO THIS FOR EVERY SINGLE INDEX i in the string. BUT this checks for odd length palindromes, we want to also check for even length so we set the left pointer to i and the right pointer to i+1 and continue expanding normally. For index i set L,R pointers to i then expand outwards, and to check for even palindrome substrings set L=i, R=i+1
@@satyamkumarjha8152 DP is o(n^2) time and space, the most optimal solution is the algorithm in this video except saving L, R indices of res instead of the whole string, which is o(n^2) time and o(1) space
Thanks for the amazing explanation. I also have a quick comment. In the while loop, we can add a condition to exit the loop once the resLen variable reaches the maximum Length(len(s)). By doing this, we can stop the iteration once the given entire string is a palindrome and skip iterating through the right indices as the middle element. [while l>=0 and r< len(s) and s[l] == s[r] and resLen!=len(s)]:
I had the same question. The reason it can be considered DP is because when we expand outwards by one character, the check for whether it's a palindrome is O(1) because we rely on the previous calculation of the inner string of characters. Relying on a previous calculation like that is the basis of dynamic programming. This optimization is critical as it brings the solution down from O(n^3) to O(n^2).
The Neetcode Practice page lists this problem as 1-D Dynamic Programming. The solution in this video is perfectly fine. But *it doesn't use DP* . This video: O(n^2) time, O(1) space 1-D DP: O(n) time, O(n) space.
I believe his expanding mid solution is easier to come up with in an interview and uses constant memory. AFAIK the dp solution is O(n^2) time and space. Do you have an implementation for O(n)?
@@chihoang910 No, I don't know an O(n) solution. If anyone has one, please let us know. 🙂 (Also, I updated my comment. TLDR: the solution in the video isn't DP.)
Hi everybody I want to share the answer to this problem using dp, the code is well commented (I hope), also congrats @NeetCode for his excellent explanations def longest_palindromic_substring(s): n = len(s) if n == 1: return s dp = [[False] * n for _ in range(n)]# 2D array of n x n with all values set to False longest_palindrome = ""
# single characters are palindromes for i in range(n): dp[i][i] = True longest_palindrome = s[i]
# check substrings of length 2 and greater for length in range(2, n+1): # size of the window to check for i in range(n - length + 1): # iteration limit for the window j = i + length - 1 # end of the window if s[i] == s[j] and (length == 2 or dp[i+1][j-1]): # dp[i+1][j-1] this evaluates to True if the substring between i and j is a palindrome dp[i][j] = True # set the end points of the window to True if length > len(longest_palindrome): longest_palindrome = s[i:j+1] # update the longest palindrome
return longest_palindrome print(longest_palindromic_substring("bananas")) # Output: 'anana' # The time complexity of this solution is O(n^2) and the space complexity is O(n^2).
The solution is crystal clear and very easy to understand, although I'm still confused why is this problem placed under Dynamic Programming category? Can anyone explain?
I like when you post that it took time to you also to solve it, many people, including me, we get scaried if we do not solve it fast as "everybody does"!! Thanks again.
Thanks this is definitely a different kind of solution, especially for a dynamic programming type problem but you explained it and made it look easier than the other solutions I've seen. Also for people wondering, the reason why he did if (r - l + 1), think about sliding window, (windowEnd - windowStart + 1), this is the same concept, he is getting the window size aka the size of the palindrome and checking if its bigger than the current largest palindrome.
But unfortunately string slice operation would also cost linear time as well so u can store the range index instead of updating the res with string everytime
This is two pointer problem instead of DP problem no? It doesn't really solve subproblem and does not have recurrence relationship. The category in the Neetcode Roadmap got me. I spent quite a while trying to come up with the recurrence function but no avail :D
The way I solved it to create a dp table. The function is dp[i,j] = true if i == j Else true if s[i] == s[j] and inner substring is a plaindrome too (i e dp[i+1][j-1]
Thanks for the amazing explanation! I managed to double the performance by doing this: While iterating s, you can also check if s itself is a palindrome, and if so, you don't need to iterate the other half of it (since s will be the largest palindrome, and therefore be the answer).
I was using while left in range(len(s)) and it definitely make my solution hit the time limit. Able to pass the test cases after change it to left > 0. Thanks Neet!
I tried so hard with recursive calls and cache, thank you for the explanation! I wonder why I never come up with that clever idea though. I thought about expanding out from the center, but I was trying to find "the center (of answer)" and expand out only once.
Very good solution. If you add at the beginning of for loop the line "if resLen > 0 and len(s) - i - 1 < resLen // 2 : break" you will speed up the algorithm faster than 90 % submissions and get a runtime of about 730 ms. The idea is if you already have the palindrome you don't have to loop till the end of "s". You can break the loop after the distance till the end of "s" is less than resLen / 2.
For me it was the separating out of even versus odd checking. I was moving my pointers all at once, thus missing the edge case where longest length == 2 (e.g. 'abcxxabc'). While separating out duplicates code, it does do the trick.
Got this question in Leetcode's mock online assessment and had no idea that it was a medium. I didn't even know where to begin. I guess I still need to keep doing easy before I move on to the mediums.
what i did was expand the center first( find the cluster of the center character - "abbba", in the given example find the index of the last b), then expand the edges, that way its irrelevant if its even or odd, each iteration will start from the next different character.
why is there no check to see if the length is odd or even? because otherwise the code would go through both while loops right? That part is a little confusing
Thats what I was thinking. The string is either even length or odd length. There should have been an if condition, otherwise it would compute it additionally
I did that and it didn't work. For example: s = "ab" This has an even length so we put l, r = i, i + 1. But since s[0] != s[1], it won't even pass the if condition in the while loop and return "". The expected output should be "a" as a single character also counts as a palindromic substring. Hence, not checking if the length is odd or even allows our program to go into both while loops wherein l, r = i, i in another while loop. This will work as s[0] == s[0]. Hence the res gets updated to "a" and matches the expected output.
Simplest solution: def longestPalindrome(self, s: str) -> str: longest = "" for i in range(len(s)): # checking for even and odd strings for r_off in range(2): r, l = i + r_off, i while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 longest = max(longest, s[l + 1 : r], key=len) return longest
Could you explain why this is a dynamic programming problem? How would you draw a decision tree for this as you did for other dynamic programming programs like House Robber?
This problem is a bit different, since there isn't a very useful recursion/memorization solution. While this problem does have sub problems, they don't need to be stored in memory. It still has some DP aspects to it imo tho.
@@NeetCodeThank you for the reply. I just read the LeetCode solutions and saw that they cached if an inner substring is a palindrome and if it was just check the first and last letters. And then they improved to your solution to save memory. In that case, should knowing that this problem is a dynamic programing problem help me solve this? I am just wondering if I should be able to generalize to other dynamic programming problems if I knew how to do House Robber, Longest Palindrome etc. since every question can be different? Cause right now I feel like for the same topic of interview question, different problems might seem like they have similar ideas but have totally different approaches. How will I ever be ready to solve an unseen interview question then? I hope you could guide my mindset in the right direction. Thank you.
I haven’t figured out the right way to solve this. Your approach starts from the left to see if the first character is the longest palindromic substring, then increments one character at a time until getting through the entire string. Why not start from the middle? Isn’t that the best case?
If the input is "ac", the answer will go wrong due to the result should be "a" or "c". This question should point out whether a single letter can be a palindrome.
No.. its working don't try to add extra code for checking is it odd or even.. first i got the same issue and after the debug i removed the odd or even check and got the answer
I write a function to make the code more neet. Here is my solution: class Solution: def longestPalindrome(self, s: str) -> str: res = "" resLen = 0 def isPalindrome(l, r): nonlocal res, resLen while l >= 0 and r < len(s) and s[l] == s[r]: if (r - l + 1) > resLen: res = s[l:r+1] resLen = r - l + 1 l, r = l - 1, r + 1 for i in range(len(s)): # odd length isPalindrome(i, i) # even length isPalindrome(i, i + 1) return res
damn i need more than 1 days to solve it with brute force technique, and when you said we can check it from the middle and will save so much time, i think... amazing you're right, how can im not thinking about that..
You tagged this problem as 1D DP in the Neetcode roadmap but the solution you gave is not a DP solution, a rather clever and more performant one but not DP. I think if you are going to use the DP solution, then this problem is better tagged as 2D DP.
Love the solution. I was wondering why this is under a "dynamic programming" category. I thought that dynamic programming should have some version of updating one or more values in one iteration that are then used in some other iteration. Having found a longest palindromic string upto a value of the center index, we do not seem to have a reason for using that information at another value of a center index.
The odd case does not cover any of the possible even cases, so for example lets say the given word is baab: At 1st iteration: we get b, and since left is empty, we get 1 At 2nd iteration: we get a, then left is b, right is a, we get nothing At 3d iteration: again we dont get anything since left is a, right is b So we need the one for the even case, now we can use left and right pointers to get a result of even string. At 1st iteration: We have b and a, On 2nd iteration: We have a and a, so we expand to left and right we get b and b, so we get the longest palindrome. I tried my best to explain, hope it helps.
I was hoping you’d explain manacher’s algorithm.😢 also, you can insert a character in between each letter to ensure it’s always odd length, you just have to account for that in the output
it's quite simple it you draw a square matrix of cases where rows and cols are each character of string. for the first case where your final answer is a palidrome with odd length, you alway start from the diagonal line of the matrix and expand around the center in the same speed. that's why l and r are set to the same index for the second case where your palindrome is even length, you would start from two points along the diagonal but now two parallel lines then start expand the same
something I am very confused about is the iteration of i , i is supposed to start from mid point , but with i in range(len(s)) , it is just starting from 0 to the last index .
I am pretty sure my duct tape solution is O(N^3) but it still barely made the Time limit so I am here checking how one could solve it better. Making a center pivot and growing outwards is a very elegant solution indeed
why do we start at middle? what if the string was for example "adccdeaba"? The longest palindrom here is "aba", but wouldn't your code give "d" instead, because it is the only case that'd work with s[l] == s[r]? i don't understand what am I missunderstanding
🚀 neetcode.io/ - A better way to prepare for Coding Interviews
@NeetCode make a video on Manachar's algo. I couldn't wrap my head around it
Wouldn't this solution be O(n^3) because s[l:r+1] could make a copy of s for each iteration? An improvement would be to store the indices in variables like res_l and res_r when there is a larger palindrome instead of storing the string itself in res. Then, outside of the loops, return s[res_l:res_r].
Good catch! you're exactly correct, and your proposed solution would be O(n^2). I hope the video still explains the main idea, but thank you for pointing this out. I will try to catch mistakes like this in the future.
Hey Devon Fulcher, Hii, if you don't mind can you please share your code, it would increase my knowledge in approaching these huge time complexity questions
@@shivakumart7269 Here you go leetcode.com/problems/longest-palindromic-substring/discuss/1187935/Storing-string-indices-vs.-using-substring! My small fix doesn't seem to make the runtime much faster in terms of ms but it is more correct in terms of algorithmic complexity.
@@devonfulcher It says, topic does not exist
Hi Devon, do you mind explaining why s[l:r + 1] would result in a O(N^3)? How does making a copy of s for each iteration make the solution worse? Thank you.
I looked at solutions from other people, but your explanation was the. best. In 8 mins, you explained a 30 min solution.
Love your vids. I swear you're the best leetcode tutorial out there. You get to the point and are easy to understand.
It's also super useful that he explains the time complexity of the solutions.
man I have the exact feeling!!!
I only check this one channel for all questions
time complexity = O(|s|^2)
spcae complexity = O(1)
class Solution {
private:
string expandAroundCenter(string s, int left, int right) {
int n = s.length();
while (left >= 0 && right < n && s[left] == s[right]) {
left--;
right++;
}
return s.substr(left + 1, right - left - 1);
}
public:
string longestPalin (string S) {
int n = S.length();
if (n < 2) {
return S;
}
string longestPalindrome = S.substr(0, 1); // default to the first character
for (int i = 0; i < n - 1; i++) {
string palindromeOdd = expandAroundCenter(S, i, i);
if (palindromeOdd.length() > longestPalindrome.length()) {
longestPalindrome = palindromeOdd;
}
string palindromeEven = expandAroundCenter(S, i, i + 1);
if (palindromeEven.length() > longestPalindrome.length()) {
longestPalindrome = palindromeEven;
}
}
return longestPalindrome;
}
};
Thanks (this isn’t a dynamic programming problem but it’s marked as dynamic programming on neetcode website)
TODO:- take notes in onenote and implement
Trick is to expand outward at each character (expanding to the left and right) to check for palindrome. BAB if you expand outward from A you will check that left and right pointers are equal, while they’re equal keep expanding. WE DO THIS FOR EVERY SINGLE INDEX i in the string.
BUT this checks for odd length palindromes, we want to also check for even length so we set the left pointer to i and the right pointer to i+1 and continue expanding normally.
For index i set L,R pointers to i then expand outwards, and to check for even palindrome substrings set L=i, R=i+1
This can be solved with dp though
@@thezendawgeven faster?
@@samuraijosh1595 yes,the solution proposed in this video takes n^3 time complexity whereas the solution using dp takes only n^2
@@satyamkumarjha8152 DP is o(n^2) time and space, the most optimal solution is the algorithm in this video except saving L, R indices of res instead of the whole string, which is o(n^2) time and o(1) space
It can be solved with DP, but it would be 2D DP I think
U are a true genius. Great Explanation because no else in entire youtube has explained it better than you.
Thanks for the amazing explanation. I also have a quick comment. In the while loop, we can add a condition to exit the loop once the resLen variable reaches the maximum Length(len(s)). By doing this, we can stop the iteration once the given entire string is a palindrome and skip iterating through the right indices as the middle element. [while l>=0 and r< len(s) and s[l] == s[r] and resLen!=len(s)]:
you're my leetcode savior!
Haha I appreciate it 😊
Why is this considered to be a dynamic programming example?
It is
Great question, I’m wondering the same
There is a DP way to do it you can put all the substrings in a dp table and check for if it’s palindrome
This solution is without dp, it can be solved with dp too but this isn’t it
I had the same question. The reason it can be considered DP is because when we expand outwards by one character, the check for whether it's a palindrome is O(1) because we rely on the previous calculation of the inner string of characters. Relying on a previous calculation like that is the basis of dynamic programming. This optimization is critical as it brings the solution down from O(n^3) to O(n^2).
I've been scratching my head on this problem for a few days thank you for your clean explanation and video!
This was definitely the best way to finish my day, with an AWESOME explanation
The Neetcode Practice page lists this problem as 1-D Dynamic Programming.
The solution in this video is perfectly fine. But *it doesn't use DP* .
This video: O(n^2) time, O(1) space
1-D DP: O(n) time, O(n) space.
I'm glad to see that I'm not the only one confused here.
@@o3_v3 it is it has O(1) memory, and dp has O(n) memory
I believe his expanding mid solution is easier to come up with in an interview and uses constant memory. AFAIK the dp solution is O(n^2) time and space. Do you have an implementation for O(n)?
@@chihoang910 No, I don't know an O(n) solution. If anyone has one, please let us know. 🙂
(Also, I updated my comment. TLDR: the solution in the video isn't DP.)
Hi everybody I want to share the answer to this problem using dp, the code is well commented (I hope), also congrats @NeetCode for his excellent explanations
def longest_palindromic_substring(s):
n = len(s)
if n == 1:
return s
dp = [[False] * n for _ in range(n)]# 2D array of n x n with all values set to False
longest_palindrome = ""
# single characters are palindromes
for i in range(n):
dp[i][i] = True
longest_palindrome = s[i]
# check substrings of length 2 and greater
for length in range(2, n+1): # size of the window to check
for i in range(n - length + 1): # iteration limit for the window
j = i + length - 1 # end of the window
if s[i] == s[j] and (length == 2 or dp[i+1][j-1]):
# dp[i+1][j-1] this evaluates to True if the substring between i and j is a palindrome
dp[i][j] = True # set the end points of the window to True
if length > len(longest_palindrome):
longest_palindrome = s[i:j+1] # update the longest palindrome
return longest_palindrome
print(longest_palindromic_substring("bananas"))
# Output: 'anana'
# The time complexity of this solution is O(n^2) and the space complexity is O(n^2).
Thanks, this is what i came for.
The solution is crystal clear and very easy to understand, although I'm still confused why is this problem placed under Dynamic Programming category? Can anyone explain?
I like when you post that it took time to you also to solve it, many people, including me, we get scaried if we do not solve it fast as "everybody does"!! Thanks again.
Thanks this is definitely a different kind of solution, especially for a dynamic programming type problem but you explained it and made it look easier than the other solutions I've seen.
Also for people wondering, the reason why he did if (r - l + 1), think about sliding window, (windowEnd - windowStart + 1), this is the same concept, he is getting the window size aka the size of the palindrome and checking if its bigger than the current largest palindrome.
Wait, why is this classified as a DP problem? Your solution was my first thought -- and what I ended up implementing, thinking it was incorrect.
But unfortunately string slice operation would also cost linear time as well so u can store the range index instead of updating the res with string everytime
This is two pointer problem instead of DP problem no?
It doesn't really solve subproblem and does not have recurrence relationship. The category in the Neetcode Roadmap got me. I spent quite a while trying to come up with the recurrence function but no avail :D
The way I solved it to create a dp table. The function is
dp[i,j] = true if i == j
Else true if s[i] == s[j] and inner substring is a plaindrome too (i e dp[i+1][j-1]
Wait a minute. I've been so conditioned to think O(n^2) is unacceptable that I didn't even consider that my first answer might be acceptable.
Good explanation! I thought the palindrome for the even case would be a lot more complicated but you had a pretty simple solution to it great vid!
Thanks for the amazing explanation!
I managed to double the performance by doing this: While iterating s, you can also check if s itself is a palindrome, and if so, you don't need to iterate the other half of it (since s will be the largest palindrome, and therefore be the answer).
You are the GOAT. Any leetcode problem I come here and 95% of time understand it
Just FYI, you can solve it in O(n) time complexity using Manacher's Algo
you cant leave us hanging like that after droppping this bomb. explain how it could be solved in O(n) time.
Made this very clear and simple
Thank you 🔥
Just like another guy said, his explanation is well packed, straight to the point. Please keep up the good work. 🔥🔥🔥
I was using while left in range(len(s)) and it definitely make my solution hit the time limit. Able to pass the test cases after change it to left > 0. Thanks Neet!
Great explanation. I was struggling with this one even after looking at answers.
I tried so hard with recursive calls and cache, thank you for the explanation! I wonder why I never come up with that clever idea though. I thought about expanding out from the center, but I was trying to find "the center (of answer)" and expand out only once.
i like your username
@@aat501 Thank you! And my cousin Lobstero should feel equally flattered :)
Damn daddy you really out here holding it down for us
Very good solution.
If you add at the beginning of for loop the line "if resLen > 0 and len(s) - i - 1 < resLen // 2 : break" you will speed up the algorithm faster than 90 % submissions and get a runtime of about 730 ms. The idea is if you already have the palindrome you don't have to loop till the end of "s". You can break the loop after the distance till the end of "s" is less than resLen / 2.
This helped me avoid TLE in leetcode.
But what if after looping till the end, the palindrome is of bigger length?
you set the l,r = i,i how is it middle
thanks for being honest and telling us that it took you a while to figure this out. It is empowering ngl
Thank you Neetcode for this video.
He is giving us quality explanations for free. Hats off. Let me get a job then I will buy you a coffee.
really enjoy your content, super informative! keep them coming
For me it was the separating out of even versus odd checking. I was moving my pointers all at once, thus missing the edge case where longest length == 2 (e.g. 'abcxxabc'). While separating out duplicates code, it does do the trick.
thanks neetcode you're out here doing holy work
Got this question in Leetcode's mock online assessment and had no idea that it was a medium. I didn't even know where to begin. I guess I still need to keep doing easy before I move on to the mediums.
how does it know it begins at middle?
what i did was expand the center first( find the cluster of the center character - "abbba", in the given example find the index of the last b), then expand the edges, that way its irrelevant if its even or odd, each iteration will start from the next different character.
This content is way better than LeetCode premium
Why's this under the 1-D DP tag
an actual beast. i had to look up the list slicing because i thought the [:stop:] value was inclusive. thanks for the great content
Thanks for the great video, but I don't think the logic for checking for palindrome works for the test input "abb", which should output "bb"
Yup right
Such amazing code. I have same idea as yours but unable to write such a concise code. AWESOME
This solution is brilliant
why is this solution considered dynamic programming? i cant see the pattern as dp.
I see acceptance rate of this question making me nervous, but see your explanation make me feel relieved :)
Never would've figured this out on my own.
why is there no check to see if the length is odd or even? because otherwise the code would go through both while loops right? That part is a little confusing
Thats what I was thinking. The string is either even length or odd length. There should have been an if condition, otherwise it would compute it additionally
I did that and it didn't work. For example: s = "ab"
This has an even length so we put l, r = i, i + 1. But since s[0] != s[1], it won't even pass the if condition in the while loop and return "". The expected output should be "a" as a single character also counts as a palindromic substring. Hence, not checking if the length is odd or even allows our program to go into both while loops wherein l, r = i, i in another while loop. This will work as s[0] == s[0]. Hence the res gets updated to "a" and matches the expected output.
At a time we need to check both scenarios one after another. not only one scenario at a time.
Simplest solution:
def longestPalindrome(self, s: str) -> str:
longest = ""
for i in range(len(s)):
# checking for even and odd strings
for r_off in range(2):
r, l = i + r_off, i
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
longest = max(longest, s[l + 1 : r], key=len)
return longest
thank you soo much , i was struggling for a long for this problem . peace finally .
Again thanks ❤
I've watched several video solution on this problem and yours is the easiest to understand. Thanks a lot!
I like the way he said "but I am too lazy to do it"
Could you explain why this is a dynamic programming problem? How would you draw a decision tree for this as you did for other dynamic programming programs like House Robber?
This problem is a bit different, since there isn't a very useful recursion/memorization solution. While this problem does have sub problems, they don't need to be stored in memory. It still has some DP aspects to it imo tho.
@@NeetCodeThank you for the reply. I just read the LeetCode solutions and saw that they cached if an inner substring is a palindrome and if it was just check the first and last letters. And then they improved to your solution to save memory.
In that case, should knowing that this problem is a dynamic programing problem help me solve this? I am just wondering if I should be able to generalize to other dynamic programming problems if I knew how to do House Robber, Longest Palindrome etc. since every question can be different?
Cause right now I feel like for the same topic of interview question, different problems might seem like they have similar ideas but have totally different approaches. How will I ever be ready to solve an unseen interview question then?
I hope you could guide my mindset in the right direction.
Thank you.
i don't know ...how i will thanks to you for such wonderful videos !! appreciated
One of the best explaination so far
I haven’t figured out the right way to solve this.
Your approach starts from the left to see if the first character is the longest palindromic substring, then increments one character at a time until getting through the entire string.
Why not start from the middle? Isn’t that the best case?
"I am kinda lazzyyyyyyyyy to copy-paste so I will type it again" XD NICE!!!
If the input is "ac", the answer will go wrong due to the result should be "a" or "c". This question should point out whether a single letter can be a palindrome.
No.. its working don't try to add extra code for checking is it odd or even..
first i got the same issue and after the debug i removed the odd or even check and got the answer
I write a function to make the code more neet. Here is my solution:
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
resLen = 0
def isPalindrome(l, r):
nonlocal res, resLen
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > resLen:
res = s[l:r+1]
resLen = r - l + 1
l, r = l - 1, r + 1
for i in range(len(s)):
# odd length
isPalindrome(i, i)
# even length
isPalindrome(i, i + 1)
return res
Thank you! Great work and very clear explanation.
your solutions are easier than the one on leetcode premium. smh. Thanks a lot! may god bless you!
This solution could be further improved using Manacher's algorithm
I got placed because of this question, I'll always be grateful to you. Plus I got placed for 7.7 lpa + 10% as a bonus
just stick with what you have, and you'll never regret about what you have. Just trust me on this
damn i need more than 1 days to solve it with brute force technique, and when you said we can check it from the middle and will save so much time, i think... amazing you're right, how can im not thinking about that..
Amazing way to simmplify the problem
You tagged this problem as 1D DP in the Neetcode roadmap but the solution you gave is not a DP solution, a rather clever and more performant one but not DP. I think if you are going to use the DP solution, then this problem is better tagged as 2D DP.
Your explanations to the hard problems are the best.
Love the solution. I was wondering why this is under a "dynamic programming" category. I thought that dynamic programming should have some version of updating one or more values in one iteration that are then used in some other iteration. Having found a longest palindromic string upto a value of the center index, we do not seem to have a reason for using that information at another value of a center index.
simplicity * 100 at 7:36 he mention , it took a while for him, gives a sense of relief.....kind of you be motivating us....thanks Neetcode
6:46 "Maybe we can use a function but I'm too lazy to do that"
Proceeds to write the entire code again instead of copy pasting.
Your explanation saved my life!!! Thank youuuu! I like how you explain you look at this question.
You are the best, thanks for this explanation, its very clear.
nuvu devudu swami 🙏🏻
Братан, хорош, давай, давай, вперёд! Контент в кайф, можно ещё? Вообще красавчик! Можно вот этого вот почаще?
I think this solution is crazy - crazy awesome!
Can you explain the logic for the even use case and setting the pointers to n, and n+ 1 respectively?
The odd case does not cover any of the possible even cases, so for example lets say the given word is baab:
At 1st iteration:
we get b, and since left is empty, we get 1
At 2nd iteration:
we get a, then left is b, right is a, we get nothing
At 3d iteration:
again we dont get anything since left is a, right is b
So we need the one for the even case, now we can use left and right pointers to get a result of even string.
At 1st iteration:
We have b and a,
On 2nd iteration:
We have a and a, so we expand to left and right we get b and b, so we get the longest palindrome.
I tried my best to explain, hope it helps.
I was hoping you’d explain manacher’s algorithm.😢 also, you can insert a character in between each letter to ensure it’s always odd length, you just have to account for that in the output
Wow! Just love the way you explain.
Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
how is it being checked whether it's an odd length or even length string? Loved your video btw!
it's quite simple it you draw a square matrix of cases where rows and cols are each character of string.
for the first case where your final answer is a palidrome with odd length, you alway start from the diagonal line of the matrix and expand around the center in the same speed. that's why l and r are set to the same index
for the second case where your palindrome is even length, you would start from two points along the diagonal but now two parallel lines then start expand the same
@@minh1391993 I appreciate your efforts but I am new to dp and it's getting hard for me to visualize
something I am very confused about is the iteration of i , i is supposed to start from mid point , but with i in range(len(s)) , it is just starting from 0 to the last index .
I am pretty sure my duct tape solution is O(N^3) but it still barely made the Time limit so I am here checking how one could solve it better. Making a center pivot and growing outwards is a very elegant solution indeed
Amazing solution you have made.
What's the complexity evaluation for this solution?
since this algorithm isn't DP, maybe you should move the problem to Arrays & Hashing section on your website
Thanks, that was a super easy explanation!💖
Tons of thanks for making these videos. This is really very helpful and video explanation is very nice . optimize and concise
best solution ever, thnx for making it looks easy
Was helpful
is this dp problem?
I calculate time complexity of your brute force solution as N Factorial - 1. "babad" 5 + 4 + 3 + 2.
That's not factorial, factorial would be 5 * 4 * 3 * 2...etc. It's quadratic because the sum of the natural numbers up to N is O(N^2).
Thanks for giving the bit of insight to your struggles...lets us know your human ;)
Very nice approach, thanks.
Isn't this a sliding window more than a dynamic programming question?
why do we start at middle? what if the string was for example "adccdeaba"? The longest palindrom here is "aba", but wouldn't your code give "d" instead, because it is the only case that'd work with s[l] == s[r]?
i don't understand what am I missunderstanding
thanks for your explanation. my comment: instead of updating the resLen, you might just use len(res) to check for each if condition
Your naive soln actually will be O(n^4) and optimised one will be O(n^3), Need to consider TC that substring will take while copying string