Longest Palindromic Substring - Python - Leetcode 5

Поделиться
HTML-код
  • Опубликовано: 5 окт 2024

Комментарии • 428

  • @NeetCode
    @NeetCode  3 года назад +27

    🚀 neetcode.io/ - A better way to prepare for Coding Interviews

    • @serioussam2071
      @serioussam2071 11 месяцев назад +1

      @NeetCode make a video on Manachar's algo. I couldn't wrap my head around it

  • @devonfulcher
    @devonfulcher 3 года назад +585

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

    • @NeetCode
      @NeetCode  3 года назад +330

      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.

    • @shivakumart7269
      @shivakumart7269 3 года назад +13

      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

    • @devonfulcher
      @devonfulcher 3 года назад +2

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

    • @shivakumart7269
      @shivakumart7269 3 года назад +3

      @@devonfulcher It says, topic does not exist

    • @beary58
      @beary58 2 года назад +10

      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.

  • @rishabhjain4546
    @rishabhjain4546 3 года назад +27

    I looked at solutions from other people, but your explanation was the. best. In 8 mins, you explained a 30 min solution.

  • @derek_chi
    @derek_chi 3 года назад +143

    Love your vids. I swear you're the best leetcode tutorial out there. You get to the point and are easy to understand.

    • @mike19558
      @mike19558 3 года назад +2

      It's also super useful that he explains the time complexity of the solutions.

    • @littlebox4328
      @littlebox4328 3 года назад +1

      man I have the exact feeling!!!

    • @mama1990ish
      @mama1990ish 3 года назад +5

      I only check this one channel for all questions

    • @navadeepiitbhilai9470
      @navadeepiitbhilai9470 Год назад

      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;
      }
      };

  • @mostinho7
    @mostinho7 Год назад +17

    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

    • @thezendawg
      @thezendawg 11 месяцев назад

      This can be solved with dp though

    • @samuraijosh1595
      @samuraijosh1595 11 месяцев назад

      @@thezendawgeven faster?

    • @satyamkumarjha8152
      @satyamkumarjha8152 8 месяцев назад

      @@samuraijosh1595 yes,the solution proposed in this video takes n^3 time complexity whereas the solution using dp takes only n^2

    • @EE12345
      @EE12345 6 месяцев назад

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

    • @yassermorsy8481
      @yassermorsy8481 День назад

      It can be solved with DP, but it would be 2D DP I think

  • @AbdulWahab-jl4un
    @AbdulWahab-jl4un 2 месяца назад +2

    U are a true genius. Great Explanation because no else in entire youtube has explained it better than you.

  • @sowbaranikab1302
    @sowbaranikab1302 2 года назад +4

    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)]:

  • @jacqueline1874
    @jacqueline1874 4 года назад +20

    you're my leetcode savior!

    • @NeetCode
      @NeetCode  4 года назад +3

      Haha I appreciate it 😊

  • @yilmazbingol4838
    @yilmazbingol4838 3 года назад +34

    Why is this considered to be a dynamic programming example?

    • @anishkarthik4309
      @anishkarthik4309 Год назад

      It is

    • @judahb3ar
      @judahb3ar Год назад +2

      Great question, I’m wondering the same

    • @hasansihab3555
      @hasansihab3555 Год назад +2

      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

    • @Briansilasluke
      @Briansilasluke Год назад +2

      This solution is without dp, it can be solved with dp too but this isn’t it

    • @Dermotten
      @Dermotten 6 месяцев назад +1

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

  • @doodle_pug
    @doodle_pug 3 года назад +7

    I've been scratching my head on this problem for a few days thank you for your clean explanation and video!

  • @federicoestape4111
    @federicoestape4111 3 года назад +32

    This was definitely the best way to finish my day, with an AWESOME explanation

  • @davidespinosa1910
    @davidespinosa1910 6 месяцев назад +10

    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.

    • @o3_v3
      @o3_v3 5 месяцев назад

      I'm glad to see that I'm not the only one confused here.

    • @FirstnameLastname-rm2qi
      @FirstnameLastname-rm2qi 2 месяца назад

      @@o3_v3 it is it has O(1) memory, and dp has O(n) memory

    • @chihoang910
      @chihoang910 9 дней назад

      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)?

    • @davidespinosa1910
      @davidespinosa1910 9 дней назад

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

  • @enriqeu23452
    @enriqeu23452 Год назад +41

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

    • @shakthi6351
      @shakthi6351 Год назад +2

      Thanks, this is what i came for.

  • @amanladla6675
    @amanladla6675 4 месяца назад +3

    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?

  • @rodrigoferrari8314
    @rodrigoferrari8314 2 года назад +1

    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.

  • @symbol767
    @symbol767 2 года назад +3

    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.

  • @Dhruvbala
    @Dhruvbala 3 месяца назад +2

    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.

  • @arnabpersonal6729
    @arnabpersonal6729 3 года назад +7

    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

  • @illu1na
    @illu1na Год назад +3

    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

    • @gradientO
      @gradientO 11 месяцев назад

      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]

  • @IsomerMashups
    @IsomerMashups 3 года назад +6

    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.

  • @matthewsarsam8920
    @matthewsarsam8920 2 года назад +7

    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!

  • @Lucas-nz6qt
    @Lucas-nz6qt 5 месяцев назад

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

  • @Mohib3
    @Mohib3 2 года назад

    You are the GOAT. Any leetcode problem I come here and 95% of time understand it

  • @biplabsarkar3567
    @biplabsarkar3567 Год назад +2

    Just FYI, you can solve it in O(n) time complexity using Manacher's Algo

    • @samuraijosh1595
      @samuraijosh1595 11 месяцев назад +1

      you cant leave us hanging like that after droppping this bomb. explain how it could be solved in O(n) time.

  • @9-1939
    @9-1939 27 дней назад

    Made this very clear and simple
    Thank you 🔥

  • @brandonwie4173
    @brandonwie4173 2 года назад +5

    Just like another guy said, his explanation is well packed, straight to the point. Please keep up the good work. 🔥🔥🔥

  • @inikotoran
    @inikotoran 3 года назад +2

    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!

  • @diludhillonz
    @diludhillonz 3 года назад +2

    Great explanation. I was struggling with this one even after looking at answers.

  • @shrimpo6416
    @shrimpo6416 2 года назад +5

    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
      @aat501 2 года назад +3

      i like your username

    • @shrimpo6416
      @shrimpo6416 2 года назад +4

      @@aat501 Thank you! And my cousin Lobstero should feel equally flattered :)

  • @vantran321
    @vantran321 2 года назад +1

    Damn daddy you really out here holding it down for us

  • @victorvelmakin9907
    @victorvelmakin9907 3 года назад +3

    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.

    • @bidishadas832
      @bidishadas832 2 года назад

      This helped me avoid TLE in leetcode.

    • @krishnanspace
      @krishnanspace 8 месяцев назад

      But what if after looping till the end, the palindrome is of bigger length?

  • @taran7649
    @taran7649 2 года назад +2

    you set the l,r = i,i how is it middle

  • @mehmetnadi8930
    @mehmetnadi8930 2 года назад

    thanks for being honest and telling us that it took you a while to figure this out. It is empowering ngl

  • @masc0648
    @masc0648 10 месяцев назад

    Thank you Neetcode for this video.

  • @sauravdeb8236
    @sauravdeb8236 3 года назад +1

    He is giving us quality explanations for free. Hats off. Let me get a job then I will buy you a coffee.

  • @calvinlai3354
    @calvinlai3354 4 года назад +8

    really enjoy your content, super informative! keep them coming

  • @Obligedcartoon
    @Obligedcartoon 2 года назад +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.

  • @supercarpro
    @supercarpro 2 года назад

    thanks neetcode you're out here doing holy work

  • @AliMalik-yt5ex
    @AliMalik-yt5ex 2 года назад

    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.

  • @christineeee96
    @christineeee96 Год назад +2

    how does it know it begins at middle?

  • @Mad7K
    @Mad7K 2 года назад

    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.

  • @rotichbill637
    @rotichbill637 2 года назад

    This content is way better than LeetCode premium

  • @chehakmalhotra7807
    @chehakmalhotra7807 Год назад +2

    Why's this under the 1-D DP tag

  • @_ipsissimus_
    @_ipsissimus_ 3 года назад

    an actual beast. i had to look up the list slicing because i thought the [:stop:] value was inclusive. thanks for the great content

  • @michaelw8908
    @michaelw8908 2 года назад +2

    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"

  • @frzhouu2676
    @frzhouu2676 2 года назад

    Such amazing code. I have same idea as yours but unable to write such a concise code. AWESOME

  • @vishaalkumaranandan2894
    @vishaalkumaranandan2894 2 месяца назад

    This solution is brilliant

  • @Bamboo_gong
    @Bamboo_gong 2 года назад +1

    why is this solution considered dynamic programming? i cant see the pattern as dp.

  • @khangmach01
    @khangmach01 Год назад

    I see acceptance rate of this question making me nervous, but see your explanation make me feel relieved :)

  • @Aryan-pe2ii
    @Aryan-pe2ii 5 месяцев назад

    Never would've figured this out on my own.

  • @ErinTiha
    @ErinTiha 9 месяцев назад +2

    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

    • @krishnanspace
      @krishnanspace 8 месяцев назад

      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

    • @youngjun916
      @youngjun916 2 месяца назад

      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.

    • @SreedevPS
      @SreedevPS Месяц назад

      At a time we need to check both scenarios one after another. not only one scenario at a time.

  • @freyappari
    @freyappari Год назад

    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

  • @JohnWickea
    @JohnWickea Год назад

    thank you soo much , i was struggling for a long for this problem . peace finally .
    Again thanks ❤

  • @marvinxu2950
    @marvinxu2950 2 года назад

    I've watched several video solution on this problem and yours is the easiest to understand. Thanks a lot!

  • @sidazhong2019
    @sidazhong2019 2 года назад

    I like the way he said "but I am too lazy to do it"

  • @gordonlim2322
    @gordonlim2322 2 года назад +1

    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?

    • @NeetCode
      @NeetCode  2 года назад +3

      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.

    • @gordonlim2322
      @gordonlim2322 2 года назад

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

  • @aniketsinha2826
    @aniketsinha2826 2 года назад

    i don't know ...how i will thanks to you for such wonderful videos !! appreciated

  • @sulavasingha
    @sulavasingha Год назад

    One of the best explaination so far

  • @supremoluminary
    @supremoluminary 8 месяцев назад

    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?

  • @vinayakagarwal3050
    @vinayakagarwal3050 2 года назад

    "I am kinda lazzyyyyyyyyy to copy-paste so I will type it again" XD NICE!!!

  • @Angx_only
    @Angx_only Год назад +2

    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.

    • @SreedevPS
      @SreedevPS Месяц назад

      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

  • @ahmetcemek
    @ahmetcemek Месяц назад +1

    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

  • @jiahaoguo8882
    @jiahaoguo8882 4 года назад +3

    Thank you! Great work and very clear explanation.

  • @mojojojo1211
    @mojojojo1211 2 года назад

    your solutions are easier than the one on leetcode premium. smh. Thanks a lot! may god bless you!

  • @ognjenpingvin
    @ognjenpingvin Год назад +1

    This solution could be further improved using Manacher's algorithm

  • @peteremmanuel7578
    @peteremmanuel7578 Месяц назад

    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

    • @peteremmanuel7578
      @peteremmanuel7578 Месяц назад

      just stick with what you have, and you'll never regret about what you have. Just trust me on this

  • @dbappz8293
    @dbappz8293 5 месяцев назад

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

  • @kartiksoni5877
    @kartiksoni5877 2 года назад

    Amazing way to simmplify the problem

  • @AramDovlatyan
    @AramDovlatyan 9 месяцев назад +1

    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.

  • @CodeReviewer
    @CodeReviewer 3 года назад +1

    Your explanations to the hard problems are the best.

  • @meeradad
    @meeradad 6 месяцев назад

    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.

  • @piyushupadhyay8361
    @piyushupadhyay8361 2 года назад +2

    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

  • @aptus716
    @aptus716 Год назад

    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.

  • @amandatao9622
    @amandatao9622 3 года назад

    Your explanation saved my life!!! Thank youuuu! I like how you explain you look at this question.

  • @wintersol9921
    @wintersol9921 11 месяцев назад

    You are the best, thanks for this explanation, its very clear.

  • @ambarishrishu
    @ambarishrishu 2 года назад +1

    nuvu devudu swami 🙏🏻

  • @Yosso117
    @Yosso117 Год назад

    Братан, хорош, давай, давай, вперёд! Контент в кайф, можно ещё? Вообще красавчик! Можно вот этого вот почаще?

  • @dominicxavier3128
    @dominicxavier3128 2 года назад

    I think this solution is crazy - crazy awesome!

  • @goldenboy_808
    @goldenboy_808 Год назад +1

    Can you explain the logic for the even use case and setting the pointers to n, and n+ 1 respectively?

    • @wintersol9921
      @wintersol9921 11 месяцев назад

      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.

  • @xx133
    @xx133 9 месяцев назад

    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

  • @aryanyadav3926
    @aryanyadav3926 2 года назад

    Wow! Just love the way you explain.

  • @stith_pragya
    @stith_pragya 7 месяцев назад +1

    Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @porassingh4904
    @porassingh4904 3 года назад +2

    how is it being checked whether it's an odd length or even length string? Loved your video btw!

    • @minh1391993
      @minh1391993 2 года назад +1

      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

    • @porassingh4904
      @porassingh4904 2 года назад

      @@minh1391993 I appreciate your efforts but I am new to dp and it's getting hard for me to visualize

  • @matildayipan9004
    @matildayipan9004 17 дней назад

    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 .

  • @MadpolygonDEV
    @MadpolygonDEV Год назад

    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

  • @LetszGoo
    @LetszGoo 2 года назад

    Amazing solution you have made.

  • @PippyPappyPatterson
    @PippyPappyPatterson 2 года назад +1

    What's the complexity evaluation for this solution?

  • @EE12345
    @EE12345 6 месяцев назад

    since this algorithm isn't DP, maybe you should move the problem to Arrays & Hashing section on your website

  • @edwythefair5215
    @edwythefair5215 3 года назад +1

    Thanks, that was a super easy explanation!💖

  • @netraamrale3850
    @netraamrale3850 2 года назад +1

    Tons of thanks for making these videos. This is really very helpful and video explanation is very nice . optimize and concise

  • @dangbey4822
    @dangbey4822 Год назад

    best solution ever, thnx for making it looks easy

  • @luckychitundu1070
    @luckychitundu1070 2 года назад +1

    Was helpful

  • @allandogreat
    @allandogreat 2 года назад +1

    is this dp problem?

  • @supremoluminary
    @supremoluminary 3 года назад +1

    I calculate time complexity of your brute force solution as N Factorial - 1. "babad" 5 + 4 + 3 + 2.

    • @raymondtan2795
      @raymondtan2795 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).

  • @travisc9436
    @travisc9436 3 года назад +1

    Thanks for giving the bit of insight to your struggles...lets us know your human ;)

  • @sharad_dutta
    @sharad_dutta 2 года назад

    Very nice approach, thanks.

  • @jacobwilliams9898
    @jacobwilliams9898 2 года назад +1

    Isn't this a sliding window more than a dynamic programming question?

  • @delsix1222
    @delsix1222 5 месяцев назад

    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

  • @chloexie6576
    @chloexie6576 2 года назад +1

    thanks for your explanation. my comment: instead of updating the resLen, you might just use len(res) to check for each if condition

  • @sidforreal
    @sidforreal 2 года назад

    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