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.
I looked at solutions from other people, but your explanation was the. best. In 8 mins, you explained a 30 min solution.
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've been scratching my head on this problem for a few days thank you for your clean explanation and video!
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.
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;
}
};
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!
This was definitely the best way to finish my day, with an AWESOME explanation
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.
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
@@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
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).
I've watched several video solution on this problem and yours is the easiest to understand. Thanks a lot!
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.
Great explanation. I was struggling with this one even after looking at answers.
really enjoy your content, super informative! keep them coming
Just like another guy said, his explanation is well packed, straight to the point. Please keep up the good work. 🔥🔥🔥
Thank you! Great work and very clear explanation.
Your explanation saved my life!!! Thank youuuu! I like how you explain you look at this question.
thanks neetcode you're out here doing holy work
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 being honest and telling us that it took you a while to figure this out. It is empowering ngl
Tons of thanks for making these videos. This is really very helpful and video explanation is very nice . optimize and concise
Thank you for this! Great concise explanations. Subscribed!
Amazingly neat solution and enlightening explanation as always!
Such amazing code. I have same idea as yours but unable to write such a concise code. AWESOME
Wow! Just love the way you explain.
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).
Thank you for sharing a good idea. I am so enjoying to learn.
Thanks, that was a super easy explanation!💖
thank you soo much , i was struggling for a long for this problem . peace finally .
Again thanks ❤
i don't know ...how i will thanks to you for such wonderful videos !! appreciated
Great explanation and easy to understand. Thanks for the video
One of the best explaination so far
Thank you Neetcode for this 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]
I see acceptance rate of this question making me nervous, but see your explanation make me feel relieved :)
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.
Great explanation! By far the best solution.
Amazing way to simmplify the problem
Very nice approach, thanks.
You are the best, thanks for this explanation, its very clear.
Amazing solution you have made.
Great explanation, as usual!
hey buddy u earned my subs!! your explanation is very awesome keep going love your content😘
I think this solution is crazy - crazy awesome!
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.
Perfect. Thank you!
best solution ever, thnx for making it looks easy
You saved my day :D, thanks.
Братан, хорош, давай, давай, вперёд! Контент в кайф, можно ещё? Вообще красавчик! Можно вот этого вот почаще?
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.
Awesome content!! Kudos :)
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)
Thank you very much for your videos mate. Just wondering what software you are using to draw on? it looks very nice.
Why is this considered to be a dynamic programming example?
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).
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
Your explanations to the hard problems are the best.
Great explanation !!
your solutions are easier than the one on leetcode premium. smh. Thanks a lot! may god bless you!
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..
Beautiful Solution
Thanks for the solution
thanks for your explanation. my comment: instead of updating the resLen, you might just use len(res) to check for each if condition
Great explanation
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 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.
@@aat501 Thank you! And my cousin Lobstero should feel equally flattered :)
This content is way better than LeetCode premium
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 :)
He is giving us quality explanations for free. Hats off. Let me get a job then I will buy you a coffee.
Great video!
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.
Thanks for giving the bit of insight to your struggles...lets us know your human ;)
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).
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?
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
Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
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.
good one bruh❤️
i dont think i have a seen easier way to get this .. i always struggle with the dp 2d array and make mistake .. thanks for making it clear 👍🏻
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.
smooth af
Awesome !!
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
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.
But what if after looping till the end, the palindrome is of bigger length?
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
Was helpful
Thanks!
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.
I like the way he said "but I am too lazy to do it"
You are the best guy
Precise and Clear content. Thanks a lot.
you are an awesome software engineer. Team whos working with you would be so lucky to have you dude.
Thank you
very clear
🚀 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