Longest Palindromic Substring - Python - Leetcode 5
Vložit
- čas přidán 9. 07. 2024
- 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Twitter: / neetcode1
Discord: / discord
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
Problem link: neetcode.io/problems/longest-...
0:00 - Conceptual Solution
4:30 - Coding solution
#Coding #CodingInterview #GoogleInterview
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission. - Věda a technologie
🚀 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;
}
};
I've been scratching my head on this problem for a few days thank you for your clean explanation and video!
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)]:
This was definitely the best way to finish my day, with an AWESOME explanation
You are the GOAT. Any leetcode problem I come here and 95% of time understand it
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!
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!
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.
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.
you're my leetcode savior!
Haha I appreciate it 😊
really enjoy your content, super informative! keep them coming
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 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
@@felixtheaeven 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
I've watched several video solution on this problem and yours is the easiest to understand. Thanks a lot!
Thank you! Great work and very clear explanation.
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.
Just like another guy said, his explanation is well packed, straight to the point. Please keep up the good work. 🔥🔥🔥
Thank you for this! Great concise explanations. Subscribed!
Great explanation. I was struggling with this one even after looking at answers.
thanks neetcode you're out here doing holy work
Your explanation saved my life!!! Thank youuuu! I like how you explain you look at this question.
Amazingly neat solution and enlightening explanation as always!
Tons of thanks for making these videos. This is really very helpful and video explanation is very nice . optimize and concise
an actual beast. i had to look up the list slicing because i thought the [:stop:] value was inclusive. thanks for the great content
Thank you for sharing a good idea. I am so enjoying to learn.
Wow! Just love the way you explain.
thanks for being honest and telling us that it took you a while to figure this out. It is empowering ngl
Thanks, that was a super easy explanation!💖
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.
Great explanation, as usual!
Great explanation and easy to understand. Thanks for the video
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]
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).
Thank you very much for your videos mate. Just wondering what software you are using to draw on? it looks very nice.
One of the best explaination so far
i don't know ...how i will thanks to you for such wonderful videos !! appreciated
Such amazing code. I have same idea as yours but unable to write such a concise code. AWESOME
hey buddy u earned my subs!! your explanation is very awesome keep going love your content😘
Great explanation! By far the best solution.
Perfect. Thank you!
thank you soo much , i was struggling for a long for this problem . peace finally .
Again thanks ❤
You saved my day :D, thanks.
how would it get whether the string will go in first while loop or second while loop as no condition is mentioned for checking even or odd length . I am not able to get it
Very nice approach, thanks.
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.
Brilliant Explanation bro. You got a new subscriber.Great job.
Thanks, glad it was helpful
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 see acceptance rate of this question making me nervous, but see your explanation make me feel relieved :)
hey neet code for the even string "adam" "ada" forms a palliamdrom; I could not get the code the work with this logic for even length string with substrings having palliandrome. Also how is l,r set to the middle when you are setting the index to start at 0?
Awesome content!! Kudos :)
Thank you Neetcode for this video.
you set the l,r = i,i how is it middle
best solution ever, thnx for making it looks easy
Amazing way to simmplify the problem
For neetcode solution, I think we could set an expanded step to cache the longest palindrome we have found for improving. Cause if we have found a 3 length palindrome already, then we do not have to do it again. I believe that gonna save a lot of time.
You are the best, thanks for this explanation, its very clear.
Amazing solution you have made.
Hello neetcode, thanks for all the AMAZING work you do here. I've been trying to come up with a solution of my own for this question and it's been sad to say the least. I tried coming up with a solution of my own because even if your solutions (especially the brute for solution) makes sense, the time complexity O(n^3) is scary. In short, it's the firs time I've ever seen a problem that could ever have such time complexities.
I actually saw this problem on leetcode before even knowing you had solved it before. So I would like to ask, do you think it's fine "learning" the brute force approach and trying the brute force approach first for all problems? Or do you just start with an optimised solution? I'm asking because it's tempting to try out a more efficient approach or a better data structure than when you try to do so with brute force. I also find myself having tunnel vision at times when I am trying the brute force approach.
Thank you so much for everything you do here again and I really hope you could ever respond to this :)
Great explanation !!
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
Really cool video, thanks for walking through it. Question: Is there a reason to track resLen or would it be just as efficient to use len(res) instead?
yes cuase this value is being updated everytime if there is a value that is bigger than what this var is already is havng uptill that point
how does it know it begins at middle?
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.
On the Neetcode Practice page, this problem is listed as 1-D Dynamic Programming. But this video doesn't use DP at all. Also, 1-D DP yields an O(n) solution, if we can calculate each table entry in constant time. But the solution in this video is O(n^2).
I'm glad to see that I'm not the only one confused here.
I think this solution is crazy - crazy awesome!
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.
your solutions are easier than the one on leetcode premium. smh. Thanks a lot! may god bless you!
He is giving us quality explanations for free. Hats off. Let me get a job then I will buy you a coffee.
This one doesn't seem to be related much to the dynamic programming stuff.. the most intuitive way to me is the same, expanding from the centre part. Thanks for your video man, it is the clearest implementation I have ever met. I implemented with the same idea, but stumble a lot and ended up with a long code(maybe because I was using pure C.. xD)
This content is way better than LeetCode premium
thanks for your explanation. my comment: instead of updating the resLen, you might just use len(res) to check for each if condition
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
Братан, хорош, давай, давай, вперёд! Контент в кайф, можно ещё? Вообще красавчик! Можно вот этого вот почаще?
I didn't get the part where you say that you would be starting from the mid position and will travel both sides i.e left and right but you also start your pointers from the starting point i.e 0. Could you please explain how exactly this works? I have watched your video thrice but cannot understand how exactly it is working. I want to understand where is the mid point because since l pointer is already 0 it would keep decrementing i.e -1. That is what I am able to understand.
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
May I ask why should we expand the l and r outward?
why is this solution considered dynamic programming? i cant see the pattern as dp.
Great explanation
Thanks for the solution
Great video!
Thanks for giving the bit of insight to your struggles...lets us know your human ;)
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?
Hi Neetcode, I have a question about res=[l:r+1], why r+1 though? You typed it without any explanation so I was trying to see if I can make sense of it.
It feels like if it is odd number, then like acbca, l=r=i starting from middle, each round l-1 r+1, then in the end will be s[l]=a,s[r]=a. res will be acbca, but if you do res[l:r+1] at this point, there will be an empty out there, why not just [l:r]? Then I change it when I type it, I found
if there is a string is like acbcc, isn't the result should be cbcc? But it is actually cbc, and how is that l:r+1 but not l:r?
or the r
i get the code for the odd, but not that even. how does adding 1 to the right pointer make it solvable for even length stirng?
NC is checking the case where the palindromic substring is of even number in character length. In order to check that, you need to have p1 pointing to i and p2 pointing to i + 1. p2 can be i -1. It depends how you want to solve the problem.
For example, say we have abba.
In order to spot, "abba", you need p1 = 1 and p2 = 1 + 1 = 2.
You can't get abba, if both of your pointers, p1 and p2 are 1.
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 :)
Are you referring to 1 and 2 element when you said odd and even length?
Can someone walk through what the condition if(r-l + 1) is yielding, because when I dryrun it it seems to give 1 for each iteration which would not be greater than resLength. Feeling a little confused as to how this line of code plays out in real time
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.
Beautiful Solution
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?
Your explanations to the hard problems are the best.
@neetcode - a Quick Question --- where is the variable resLen being used?
I meant I didnt see it contributing to the final res string..
Its used as a decider for next iteration whether or not to update the next result
good one bruh❤️
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..
Thanks for the content. What keyboard do you use?
I used to have a mechanical one, but now I use and prefer this really cheap logitech keyboard: amzn.to/3zQBozP
Awesome !!
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