Leetcode problem Longest Palindromic Substring (two solutions)

Sdílet
Vložit
  • čas přidán 10. 01. 2020
  • Solving a medium coding interview question from Leetcode leetcode.com/problems/longest...
    Final code: github.com/Errichto/youtube/b...
    Subscribe for more educational videos on algorithms, coding interviews and competitive programming.
    - Github repository: github.com/Errichto/youtube
    - Second YT channel for streams: / errichto2
    - FB and Twitter: / errichto & / errichto
    - Frequently Asked Questions: github.com/Errichto/youtube/w...

Komentáře • 201

  • @stanshen5207
    @stanshen5207 Před 3 lety +334

    Your first statement made me crying for 2 hours straight

  • @youssefmuhamad3213
    @youssefmuhamad3213 Před 4 lety +204

    I love your tutorials, how you go from the naive solution to the optimized one

    • @Errichto
      @Errichto  Před 4 lety +47

      Thanks :)

    • @musafirgauravv
      @musafirgauravv Před 4 lety +11

      I too liked his same approach, it helps the people who don't have the ability to see optimized solutions at the very beginning.

    • @aj9706
      @aj9706 Před 4 lety +2

      @@Errichto Given an array of integers,find the maximum value of a[i] - a[j] + a[k] with constraints I

    • @shashankmishra9238
      @shashankmishra9238 Před 4 lety

      @@aj9706 hi will seeing it as maximise ak-aj+ai and transversing i with j= i+1 and k=n-1 work?

  • @ashutoshmaheshwari833
    @ashutoshmaheshwari833 Před 4 lety +75

    This is the beauty when someone red on codeforces solves interview problems. It was so easy for you Errichto, but for the sake of your audience you explained it thoroughly. Thanks :)

  • @harshitmittal1217
    @harshitmittal1217 Před 4 lety +12

    I just love how you go from the simplest to the most optimized solution and the way you explain the process for optimizing the code.

  • @kaiovieira230
    @kaiovieira230 Před 4 lety +4

    Love this! Because this is a simpler problem (comparing others in this channel) I could understand the proccess and I've got so many things to learn. Thank you!

  • @achavan1
    @achavan1 Před 4 lety

    I really appreciate your videos. I think the intuition behind how you derive the solution is outstanding. Helps a lot to understand how you came develop an approach.

  • @harishgehlot__
    @harishgehlot__ Před 2 lety +1

    Thank you brother from another mother, everyone on CZcams showing the code of optimised approach,
    Only you showed the brute force

  • @TimHinnerkHeuer
    @TimHinnerkHeuer Před 4 lety +13

    Great stuff, Errichto! There are far more successful CZcamsrs with a greater following. BUT I think you're way ahead of them in terms of material and quality content. Would love to see more videos like this. I think at the moment you're far under rated. Keep up the good work! 😀

  • @atibhiagrawal6460
    @atibhiagrawal6460 Před 4 lety +3

    Thank you so much for these Leetcode tutorials. Absoultely love them !

  • @ShreyanGoswami
    @ShreyanGoswami Před 4 lety

    Thanks for the explanation. I came to watch your video after I solved the problem myself. I was not disappointed because you explored many options. For N^2 time complexity what I did was reversed the original string and used longest common substring between the original string and the reversed string. I got an edge case where it was finding strings of length 2 to be palindrome even if they were not.

  • @varunv6641
    @varunv6641 Před 4 lety +3

    Wow, no ads in any video.... This man is a legend

  • @BigFatSandwitch
    @BigFatSandwitch Před 4 lety +60

    The small c++ optimizations you mentioned in this video will be really helpful for me while coding. Thanks for putting out content like these

    • @deDeca1000
      @deDeca1000 Před 4 lety +9

      This optimization isn't strict to c++. When we use &, it'll compute the 2 parts of operations independently of your logical value, when we use &&, it'll check the first part and if it's false the second part will not be computed because it'll be false anyway. The same works with || and |, when we use ||, if the first part is true, the second will not be computed because the operation will be true anyway.

    • @a.yashwanth
      @a.yashwanth Před 3 lety +1

      @@deDeca1000 But this doesn't work in java.

    • @deDeca1000
      @deDeca1000 Před 3 lety

      @@a.yashwanth I guess it works too as a simple research that I did here.

    • @kruz2919
      @kruz2919 Před 3 lety

      @@a.yashwanth Yes it works in Java since I kept the length check before the string check and my solution got accepted albeit with long runtime. Just one little manoeuvre to change the verdict from TLE to Accepted.

  • @muskanagarwal7937
    @muskanagarwal7937 Před 4 lety

    I loved your way of breaking down the problem and gradually moving towards more optimized version. Would love your input on codechef problems from long challenge, cook off, lunchtime and various other categories of problem.

  • @chongluo3490
    @chongluo3490 Před 3 lety +1

    Wow, your tutorial is so cool, it gives me a more general solution for optimization which could be applied to other Leetcode problems.

  • @shahriardhruvo4333
    @shahriardhruvo4333 Před 2 lety

    You are awesooome, thank you. I love that you first write the naive solution and then explain and improve the code bit by bit :3

  • @EdinssonMelo
    @EdinssonMelo Před 4 lety

    Thx for the tutorial. I would appreciate it if you continue to share well known topics.

  • @akshobhya_8690
    @akshobhya_8690 Před 4 lety

    It is the best video I've ever seen for this problem. Your approach is awesome dude.

  • @raushankumarraman7259
    @raushankumarraman7259 Před 4 lety +1

    Your explanations of problems are awesome going from bruteforce approach to optimisation......

  • @mfaraday4044
    @mfaraday4044 Před 4 lety +1

    Mindblowing sir .
    Thankyou very much .
    Your way of explaination is unique.

  • @MrSun8080
    @MrSun8080 Před 4 lety +3

    Hi Errichto thank you for the video! I really appreciate your explanation on the problem that many users struggle. Do you mind if you could make more videos on the solution that are on the list from top 100 liked questions or top 100 interview questions that are more of a medium level from the LeetCode? this way I think more entry-medium level coders can enjoy your channel more instead of diving into your explanation on hard algorithmic questions (though I enjoy those too). Hope you can take this into a consideration! thank you always.

  • @fbru02
    @fbru02 Před 4 lety

    Excellent video !! need to bring back the second errichto

  • @ambersinghrok
    @ambersinghrok Před 4 lety

    This is the best explaination i have heard so far...plzzz me lots of videos it will be helpful for my upcoming interviews.

  • @wedding_photography
    @wedding_photography Před 4 lety +63

    I wish you covered the Manacher's algorithm as well.

  • @035asadali8
    @035asadali8 Před 2 lety

    damn amazing i just did this question today but your dynamic programming solution is faster than mine, amazing

  • @Akshaykumar-bl8ok
    @Akshaykumar-bl8ok Před 2 lety

    One Errichto video teach you a lot of extra things along with the actual solution.

  • @Xyvier
    @Xyvier Před 4 lety +6

    This is so informative and awesome!

  • @mechashadowx
    @mechashadowx Před 4 lety +6

    helpful details, that was amazing

  • @GDGET72
    @GDGET72 Před 3 lety

    Hi @Errichto, I'm wondering how making change to parameter type: (string s) -> (const string& s) would let a for loop exit with early condition hence faster-than-linear runtime. @5:58. Do you mean such change is coming from the algorithmic change and changing the paramter type would only save CPU from using extra memory to take in s? or is there something special about how for loop treats a reference ? Thanks for your time in advance

  • @nevinzheng2808
    @nevinzheng2808 Před 3 lety

    Some cool modern C++ tricks: is_palindrome could be written w/ std::equal() and rbegin(),rend(). string_view could be used to get "substrings" in constant time. I think std::binary_search() could also be applied w/ the is_palindrome predicate.

  • @arghyadeepmandal4458
    @arghyadeepmandal4458 Před rokem

    Came here for Manacher's but learnt a lot of new things 🙂.Beauty😎

  • @cojocarucosmin202
    @cojocarucosmin202 Před 4 lety

    U r such a good teacher bro

  • @MakoMako1234321
    @MakoMako1234321 Před 4 lety +25

    I'd love to watch O(n) solution from you, great video btw

    • @ritik84629
      @ritik84629 Před 4 lety

      Yes indeed.

    • @user-bc9wj2kk3x
      @user-bc9wj2kk3x Před 4 lety +2

      Notice that any palindromic substring is a common substring of s and rev(s). Now look at suffix structures in context of finding longest common substring.

  • @mesh475
    @mesh475 Před 2 lety

    You are very smart. Great explanation

  • @nurjamil6381
    @nurjamil6381 Před 3 lety

    love ur videos bro, didnt quite understand in binary search part tho, maybe with a little bit more replay i can understand it, thank you for the video!

  • @CarrotCakeMake
    @CarrotCakeMake Před 4 lety +1

    Loved it, good job. One small observation, the string "aaaaaa....aaaaa" is a degenerate case for time in your algorithm. Instead of iterating mid in 0, 1, 2, 3, 4, 5..... you could iterate mid in n/2, n/2 + 1, n/2 - 1, n/2 + 2, n/2 - 2, ....
    Then just check if mid is far enough away from the edges to make a possible new best. That puts you really close to O(n) .

    • @Errichto
      @Errichto  Před 4 lety +2

      Sure, but then there can for sure be something similar to aaa...aa that will still be slower. It just shows that a problem author has a hard job of creating good tests :D

  • @lequocthinh8992
    @lequocthinh8992 Před 3 lety

    The C++ optimization's rly helpful

  • @paragroy5359
    @paragroy5359 Před 4 lety +1

    Sir,it was really good.

  • @mukulkumar2316
    @mukulkumar2316 Před 4 lety

    plz make a video on greedy problems, i just don't know how to go about it.. always loved ur channel , thanks in advance

  • @hardikprajapati671
    @hardikprajapati671 Před 4 lety +2

    Can you please give us tutorial on Manacher's Algorithm !! i didn't understand well i have seen lots of video on Manacher's Algo!! you teaches very well!!

  • @surajbisa2941
    @surajbisa2941 Před 4 lety

    thanks a lot your great work!

  • @MrWolfgangWeiss
    @MrWolfgangWeiss Před 4 lety

    What software do you use to record yourself and screen on Ubuntu? Well done by the way.

  • @mathiaspresthagen4921
    @mathiaspresthagen4921 Před 4 lety

    I am currently through to the national finals of the informatics olympiad, but I'm not sure how to practice for it. Any tips or ideas?

  • @clivefernandes5435
    @clivefernandes5435 Před 4 lety

    Hey can u suggest a book for solving problems using methods like the monarch think u talked abt

  • @Zzznmop
    @Zzznmop Před 4 lety +12

    thank you for the lovely 25 minute explanation even though i know you can do this in 25 seconds. you are truly a gift to us all who enjoy competitive programming.
    p.s. i finally solved my first problem solved in under 5 minutes during a 3-problem online assessment, and boy did it feel amazing! Too bad the other two took about an hour each because i got ahead of myself after the first solution :P

    • @Dennis-Ong
      @Dennis-Ong Před 3 lety +1

      The high is amazing when you solve a (relative difficult ) problem. The low is terrible when you trying to understand a solution or freeze in interview.

  • @techgamer1333
    @techgamer1333 Před 4 lety

    Need More Videos Like this

  • @kenjiaoki9897
    @kenjiaoki9897 Před 3 lety +4

    Could someone kindly refer me to some material explaining the use of parity in Binary search? I did not exactly understand what @Errichto was trying to do there.

  • @anonymoussloth6687
    @anonymoussloth6687 Před 3 lety

    can someone explain the n2logn solution in detail. How is Binary search used here?

  • @jonty3551
    @jonty3551 Před 4 lety

    Hoped u would have covered manarch's algorithm as well!!!!

  • @RohanKumar-zn4qg
    @RohanKumar-zn4qg Před 4 lety

    Hello Errichto...Kindly upload videos on greedy strategy...I have solved more than 100 Div2C problems...yet whenever a greedy comes even in B ,I cant figure out whether greedy will work or not...or to which variable I should do greedy on.

  • @yuvarajanm2059
    @yuvarajanm2059 Před 3 lety

    Can anyone tell in the binary search method why we change the low and high value if it is not match with parity and we also increase the mid value if it is not match with parity instead of that can we only modify the mid value if it is not match with the parity..
    Please correct me if i am wrong.

  • @nikhilrana8800
    @nikhilrana8800 Před 3 lety

    Can anyone please explain why we add 1 in the mid-x+1? I am not able to figure it out.

  • @bharath4397
    @bharath4397 Před 4 lety

    really good explaination

  • @JV-fm5ul
    @JV-fm5ul Před 4 lety +4

    you really made me question my understanding of binary search.I didn't get that n^2logn approach.
    Edit: i get it now , thanks.

    • @devendrasingh4776
      @devendrasingh4776 Před 4 lety

      Tell me bro what you understand please . 😢😢

    • @JV-fm5ul
      @JV-fm5ul Před 4 lety

      @@devendrasingh4776 normally you search for a value in array or something but in this he was trying different answers in binary search way, it was long ago so i dont remember much.

    • @devendrasingh4776
      @devendrasingh4776 Před 4 lety

      @@JV-fm5ul but why he did even odd thing

  • @ivanleon6164
    @ivanleon6164 Před 3 lety

    you are a hero!

  • @RaGa_BABA
    @RaGa_BABA Před 3 lety +25

    errichto makes me wanna leave programming and love programming at a same time..

  • @rkalyankumar
    @rkalyankumar Před rokem

    I still didn't understand parity and binary search based solution to this problem. Any good materials for this to read & analyse?

  • @mahesh4274
    @mahesh4274 Před 4 lety +2

    Thank you for the explanation..... Hoping you will make more tutorials for beginner's like me...

    • @Errichto
      @Errichto  Před 4 lety

      So, something at this level or easier?

    • @mahesh4274
      @mahesh4274 Před 4 lety +1

      @@Errichto same level, also tips on data structures/algo if possible. You know like how to approach the problems with specific ds. Thanks for the reply.

    • @kaiovieira230
      @kaiovieira230 Před 4 lety

      For me, something at this level is great! But easier things would be awesome too

  • @sagarnikam6059
    @sagarnikam6059 Před 4 lety

    In contests like codejam and kickstart how often we need to check our program by writing brute force solution and finding cases where our optimal solution is giving WA...
    Have you used this method of checking programs in short contests also..

    • @Errichto
      @Errichto  Před 4 lety

      Codejam and Kickstart have feedback for small constraints so it isn't that important. Maybe useful if you want to find that countertest.

  • @prabhudeengautam1845
    @prabhudeengautam1845 Před 4 lety

    nice explanation!

  • @kashireddydurgadevi7998

    Helpful information thankyou

  • @rasecbadguy5600
    @rasecbadguy5600 Před 4 lety

    How to solve this problem using suffix array?

  • @subrintakarmakar5436
    @subrintakarmakar5436 Před 3 lety

    Thanks this is faster than normal dp

  • @ericcartman4799
    @ericcartman4799 Před 3 lety

    I got the first for-loop...it takes every element and expands towards the right and left side to get the largest palindrome...but can anyone explain the purpose of the second for loop?.

  • @vishalyadav7245
    @vishalyadav7245 Před 4 lety

    Great tutorial

  • @ritik84629
    @ritik84629 Před 4 lety

    What does the parity means in this video?

  • @yogeshvishnole1264
    @yogeshvishnole1264 Před 3 lety +1

    Not able to understand the second solution in which you use the parity can you explain it with some diagrams. Thanks for sush easy explanations.

  • @ankitrookies2357
    @ankitrookies2357 Před 2 lety

    nice explanation

  • @hussainrizvi1887
    @hussainrizvi1887 Před 3 lety

    Can someone explain the const string& trick to me again? Isn't the reverse() still O(N)?

  • @RAP4EVERMRC96
    @RAP4EVERMRC96 Před 2 lety

    06:08 why does comparing by reference is faster than comparing two string variables?

  • @AmanDeep-fp9ui
    @AmanDeep-fp9ui Před 4 lety +1

    Personal opinion but I would always go O(nlogn) with hashing and binary search. Its more intuitive than manacher algorithm and has just a logn extra factor.

  • @praveensinghrathore4542

    good content, you rock

  • @sanfarans
    @sanfarans Před 4 lety +3

    My first thought was hashing.
    It's possible to hash the string and hash the reversed string.
    Then to find the longest palindrome, we can for every mid point (or double mid points for even length palindromes) iterate over it's prefixes and suffixes and compare them using hashes.
    Now add binary search and we don't have to do that for every pref/suf length and just for O(logn) of them.
    If I am not mistaken the total complexity would be O(n*logn)

    • @sanfarans
      @sanfarans Před 4 lety +1

      On the other hand hashes can collide so it's kinda randomised.
      But still, risk is pretty low and can be further lowed by using pairs of hashes.

    • @Errichto
      @Errichto  Před 4 lety +4

      You are completely right, and we can even get O(N) with hashes if we increment the answer by 1 instead of binary searching :)
      I just didn't want to talk about hashes in this video, too many things for a beginner's problem.

    • @damcism
      @damcism Před 4 lety +1

      "we can for every mid point (or double mid points for even length palindromes) iterate over it's prefixes and suffixes and compare them using hashes."
      I don't understand this sentence. What do you mean by "it's prefixes"? By "it" do you mean "mid point"? If so, then what do you mean by a "prefix/suffix of a mid point"?

    • @praveenojha33
      @praveenojha33 Před 4 lety

      @@Errichto Can you please explain O(N) approach using hashes or can you give some reference to any blog or article where it is discussed ? I can only figure out O(NLogN) approach using hashes :(

    • @sanfarans
      @sanfarans Před 4 lety

      @@praveenojha33 O(n) approach is Manacher's algorithm

  • @MojahooProducer
    @MojahooProducer Před 4 lety +1

    We love youuuuu

  • @Gaurav-mq8yp
    @Gaurav-mq8yp Před 7 měsíci

    Can you please make a video on Manacher's Algorithm Errichto?

  • @bhavanprajapati4773
    @bhavanprajapati4773 Před 4 lety +1

    Please explain O(N) solution

  • @yugioh8810
    @yugioh8810 Před 4 lety +11

    I didn't understand the parity part, can anybody elaborate on that ?

    • @huan8036
      @huan8036 Před 3 lety +4

      As Errichto pointed out, using a palindrome, we can have a sub palindrome by removing two outermost value. The sub palindrome has the same parity as the original palindrome (the longer one).
      It's a fact that a palindrome with EVEN length can only have sub palindromes with EVEN length. The same thing happens to palindromes with ODD length - their sub palindromes must have ODD length too.
      Therefore, if we found a palindrome which has an EVEN length, the possible longer palindrome derived from it must have an EVEN length too (i.e they have the SAME parity).
      The parity part of Enrichto algorithm is to make sure we only looking for length that are worth checking. E.g. If we want to check if there's a palidrome with EVEN length, we will only look for EVEN length cases.
      The binary search really helps this idea to happen in O(logN); but we can implement it in O(N) just by looping through the string with the index increase by 2 each loop
      Hope this helps

    • @somesome1315
      @somesome1315 Před 3 lety

      parity is for checking the length of best_s is whether odd or even

    • @anonymoussloth6687
      @anonymoussloth6687 Před 3 lety

      @@huan8036 Can you explain a bit more of how binary search is even used here? I understand the even and odd length logic of the palindrome. But how and why Binary search is used in this is still not clear

  • @setukumarbasak6729
    @setukumarbasak6729 Před 3 lety

    Can anyone explain in details about the parity logic?

  • @faiz697
    @faiz697 Před 4 lety

    I'm doing this problem for the last 20 mins, and it seems that the test case no 26('abb') is giving me the wrong result. When I checked it by inputting the input in the test case, it's giving me the correct answer. Anyone can explain to me why is it happening?

  • @jeizart6982
    @jeizart6982 Před 4 lety +4

    watching you makes me think of quitting my job

  • @RG-sl6ix
    @RG-sl6ix Před 3 lety

    Is there any algorithm, that could be a efficient replacement for Longest Common Substring with k-mismatches

  • @ankitrookies2357
    @ankitrookies2357 Před 2 lety

    good explation

  • @sairohit8201
    @sairohit8201 Před 3 lety

    guys , what does this mean i'm seeing this for the first time
    for(int parity: {0,1} )
    {
    }
    is this a cpp thing?

  • @adityamondal1136
    @adityamondal1136 Před 4 lety

    Sir I Would request you to post a solution for CodeForces Contest 615 Div.2 Problem 1
    I really loved the video

  • @rishabhthakur2270
    @rishabhthakur2270 Před 3 lety

    Thanks :)

  • @happyhappyguy5034
    @happyhappyguy5034 Před 4 lety +2

    I don't understand the binary search one. Why do we need to consider parity?

    • @Errichto
      @Errichto  Před 4 lety +8

      Because maybe there is a palindrome of length 6 but not of length 5. So what happens if you ask "can answer be 5?" in binary search and it turns out it can't? You will now search for answer between 1 and 4.

    • @happyhappyguy5034
      @happyhappyguy5034 Před 4 lety

      @@Errichto thank you for replying, I understood it completely wrongly previously so I was very confused. But now I completely understand the solution.. :D This is very helpful btw!

  • @SlokAks
    @SlokAks Před 3 lety

    Can anyone explain to me the parity concept here?

  • @prathamnishad1033
    @prathamnishad1033 Před 4 lety +11

    on average how many problems you solve in a day (now and in the past).
    and
    Do you recommend sticking to a problem even when you cant get you head around it for days or leave it and look at the solution(or hint).

  • @MakoMako1234321
    @MakoMako1234321 Před 4 lety +1

    Why this two loops (odd/even length) are one after another? Why aren't they used based on length of string? Why it doesn't break when break when used on odd length string? (because in this case part of algorithm for odd is used first, and then part for even length is used on odd length) Why isn't it a problem?
    edit: Also why after using only one loop (for even or odd) this is not working properly?
    edit2: Ok, now I (probably) understand. One loop is for finding odd length palindrome (not odd length input), and other is for even length palindrome (not even length input). Am I right now?

  • @danieltannor6647
    @danieltannor6647 Před 4 lety

    Thanks for your explanation! A quick note: @19:04, I don't think it's N positions, but rather 2N-1 positions (because middles can be spaces between characters)

  • @minciNashu
    @minciNashu Před rokem

    string substr allocates a new string. string_view, span or plain pairs of pointers should be used in examples like this, for constant time.

  • @CarrotCakeMake
    @CarrotCakeMake Před 4 lety

    I thought of a content suggestion, some of the "hacking" rules sound fun. It might be cool to make a video where you go through some of the winner's submissions and try to find counter examples for them. I think it wouldn't be rude if you only went after the winners, or maybe if you are friends with any of them ask them if they mind.

    • @Errichto
      @Errichto  Před 4 lety +1

      They don't often submit incorrect ideas ;p strong participants have good intuition and they can prove their solution. It would be much easier to look through their wrong submissions though, but maybe I will just discuss my own mistakes?

    • @CarrotCakeMake
      @CarrotCakeMake Před 4 lety +1

      @@Errichto We don't make mistakes, we just have happy accidents!

  • @SangharshSeth
    @SangharshSeth Před 4 lety +1

    Hi Errichto

  • @pobitrapradhan9513
    @pobitrapradhan9513 Před 3 lety

    So cool

  • @KaushalJainKaushalRameshJain

    Legend

  • @nullnull6032
    @nullnull6032 Před 4 lety +1

    you are a fucking legend

  • @rajmittal5394
    @rajmittal5394 Před 2 lety

    thansk

  • @abhishekk.3977
    @abhishekk.3977 Před 3 lety

    It's 02:33 AM and holy Jesus why tf I couldn't get past the first approach. ^_^

  • @gitlit5489
    @gitlit5489 Před 4 lety

    Can u do The Skyline Problem it may be easy for you because you are the Godfather of Computational Geometry but it freaks me out xd

  • @sivaan7056
    @sivaan7056 Před 2 lety

    Never thought of binary search 🥺

  • @nikhilkumar-ot9rn
    @nikhilkumar-ot9rn Před 4 lety

    could u please once more explain that parity thing ..please!!!!!!!!!