Dp 25. Longest Common Subsequence | Top Down | Bottom-Up | Space Optimised | DP on Strings

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 ก.พ. 2022
  • Lecture Notes/C++/Java Codes: takeuforward.org/dynamic-prog...
    Problem Link: bit.ly/3pvkqUd
    Pre-req for this Series: • Re 1. Introduction to ...
    a
    Make sure to join our telegram group for discussions: linktr.ee/takeUforward
    Full Playlist: • Striver's Dynamic Prog...
    In this video, we solve the LCS Dp, this is the first problem on the pattern Strings on DP.
    If you have not yet checked our SDE sheet, you should definitely do it: takeuforward.org/interviews/s...
    You can also get in touch with me at my social handles: linktr.ee/takeUforward

ความคิดเห็น • 781

  • @sujalgupta6100
    @sujalgupta6100 ปีที่แล้ว +71

    46:05 for space optimization we don't require the loop for prev as the values are already zero in it.

  • @anweshabanerjee6241
    @anweshabanerjee6241 ปีที่แล้ว +71

    If someone is following Striver's series then this LCS is also a cakewalk..#Striver gives u confidence and you are no longer scared of dp😁

  • @pratyakshsinha6292
    @pratyakshsinha6292 ปีที่แล้ว +134

    Understood and you've completely changed my life. Doesn't matter if I get placed in a good company or not but the quality of this lectures are supreme and I will carry this knowledge for rest of my life.

    • @AdityaKumar-be7hx
      @AdityaKumar-be7hx ปีที่แล้ว +18

      Keep trying. It will work out. Dream for the day when you are so good that you REJECT your dream company.

    • @iamnoob7593
      @iamnoob7593 6 หลายเดือนก่อน

      @@AdityaKumar-be7hx Requires god level consistency to do that.

    • @idris110
      @idris110 5 หลายเดือนก่อน +1

      You will probably forget the concepts, since these are never used in the industry. What a satire !

    • @bharatravihal9646
      @bharatravihal9646 5 หลายเดือนก่อน

      🤣🤣@@idris110

    • @spoidy2025
      @spoidy2025 4 หลายเดือนก่อน

      brother are you placed

  • @art4eigen93
    @art4eigen93 ปีที่แล้ว +161

    In the future, Mr. Vikramaditya will go down as the G.O.A.T online DSA teacher.

    • @wahtNIGGA
      @wahtNIGGA 5 หลายเดือนก่อน

      Yes he is GOAT
      I am the future

    • @abhishekkarn8918
      @abhishekkarn8918 3 หลายเดือนก่อน +2

      He is already for me.

  • @manthenanagendra1077
    @manthenanagendra1077 ปีที่แล้ว +121

    putting your years of hardwork in some videos ,how lucky we are,Thanks a lot striver bhaiya for everything you are doing for us

  • @arjundevmishra7207
    @arjundevmishra7207 11 หลายเดือนก่อน +47

    Protect this guy at all costs. Thank you sir for all your hard work in making this video.

    • @mayanksingh7501
      @mayanksingh7501 2 หลายเดือนก่อน +2

      Everyone should be protected bro

  • @arunkumarsahoo1344
    @arunkumarsahoo1344 ปีที่แล้ว +17

    15:34 "You kow i am hearing you" in the background

    • @jeet-smokey
      @jeet-smokey 5 หลายเดือนก่อน +2

      So?

  • @kanikajain5627
    @kanikajain5627 10 วันที่ผ่านมา

    This was life-changing. Thank you Striver, you taught what paid courses could not for so many years. I wish I had discovered your site earlier; it would have saved so much time and energy.

  • @kartiksuman9814
    @kartiksuman9814 2 ปีที่แล้ว +52

    understood bhaiya!!! after a very long time i am back to your channel....previously i was doing a race that as soon as you upload the video, i should watch it then n there, before the next video gets uploaded in this dp series, but due to some busy schedule, i lost the race. yeah, but your quality and energy is still the same as your starting videos

  • @donno2423
    @donno2423 ปีที่แล้ว +10

    I used to be scared of Dp when I started coding journey, but when I am actually doing it, it's cake walk. Thankyou striver for sharing your knowledge.

  • @Amitchoudhary-ij4we
    @Amitchoudhary-ij4we ปีที่แล้ว +13

    I am very grateful to you for uploading this playlist. This is great!!!!!!!!!!!!!!!!!!!!!
    Understood.

  • @avimandavia6154
    @avimandavia6154 ปีที่แล้ว +5

    No other video on the topic will offer you a better explanation than this! This is just pure teaching excellence! Subscribed.

  • @duyhuynh1234
    @duyhuynh1234 ปีที่แล้ว +5

    You're a great teacher. If possible, please do problems about DP on tree. I struggle with them. Thank you!

  • @ramanahlawat398
    @ramanahlawat398 ปีที่แล้ว +4

    bro!!!!!! What an explanation, absolutely brilliant. I am starting to love coding now. Thanks

  • @World-Of-Mr-Motivater
    @World-Of-Mr-Motivater 2 วันที่ผ่านมา +1

    striver help this brother out!
    how you are staying disicplined?
    so far you are single ,right?
    how you are avoiding every distractions and focusing on your goal
    please make a video on this brother!!

  • @akashyadagouda896
    @akashyadagouda896 6 หลายเดือนก่อน +1

    Its taking while to digest this information for me ,
    Just imagine the efforts this guy is adding to make it available for everyone.

  • @mjmusic65
    @mjmusic65 ปีที่แล้ว +3

    absolutely minds bogling.i am not kidding i wasn't able to solve simple recusion questions few weeks ago now i can solve medium and hard dp questions on my own without watching videos.all i can say thank you striver.

  • @yashsinghal3404
    @yashsinghal3404 2 ปีที่แล้ว +5

    What an easy explanation, loved it !

  • @mahammedhashish9170
    @mahammedhashish9170 ปีที่แล้ว +1

    You can't find better explanation than this, Brilliant!!

  • @nottheradbrad184
    @nottheradbrad184 10 หลายเดือนก่อน

    bro striver you have taught so well that i didnt even need to watch the video,i solved the problem in all three ways,thaank you very much❤

  • @ankita716
    @ankita716 28 วันที่ผ่านมา +1

    understood, always in awe of you genius and hard working you are:)

  • @stith_pragya
    @stith_pragya 6 หลายเดือนก่อน +1

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

  • @rohan8758
    @rohan8758 หลายเดือนก่อน +1

    Nice explanation raj bhaiyan or dude, I might call you angel!🥰🥰

  • @vedxnt10
    @vedxnt10 หลายเดือนก่อน

    simple space optimization technique : just 2,3 chanes
    instead of using 2 different vectors we can just change dimension of dp to [no of previous rows we wanred + 1][no of colum]
    int longestCommonSubsequence(string s1, string s2) {
    vectordp(2, vector(s2.size()+1, 0)); // changing dimension as per need
    for(int i=1; i

  • @virgarg1012
    @virgarg1012 หลายเดือนก่อน +1

    Giving my best shot for preparing for my placements. Let's see what happens in upcoming months. Great Content

  • @sarveshamrute4982
    @sarveshamrute4982 2 ปีที่แล้ว +6

    I solved with different tabulation approach (without shifting index) as below:
    int m=text1.length();
    int n=text2.length();
    int[][] dp = new int[m][n];
    int temp=0;
    for(int i=0; i

  • @arnabroy2995
    @arnabroy2995 ปีที่แล้ว +3

    US ❤
    I should mention I am solving DSA consistently from past 1 year. Encountered this question a lot of times.
    But till date this is the best explanation boss❤

  • @varunbansal1136
    @varunbansal1136 9 หลายเดือนก่อน +1

    If someone is using java to write the code, in space optimization approach there will be error in a testcase, to resolve that error replace prev = curr with prev = curr.clone(); or else use the code snippet
    int [] temp = prev;
    prev = (curr);
    curr = temp;
    Because in java prev = curr will not create a new array but it will point both the references to same address.
    Your program would work fine.

  • @BG-lj6fw
    @BG-lj6fw ปีที่แล้ว

    understood.wonderful. amazing. hats-off. unmatchable.

  • @sypher4735
    @sypher4735 ปีที่แล้ว +6

    I’m just so thankful to you for this wonderful series, I’m honestly enjoying it dude, surely you’re one of the best!
    I even did the problem by myself so easily, i was shocked believing😂

  • @cinime
    @cinime 2 ปีที่แล้ว +1

    Understood! Awesome explanation as always, thank you very much!!!

  • @himanshuagrawal8012
    @himanshuagrawal8012 2 ปีที่แล้ว +3

    Can we do using single array if we denote prev[j-1] in a variable, keep updating it after every iteration of inner loop ?

  • @pratapsingh9638
    @pratapsingh9638 ปีที่แล้ว

    Understood,you are doing the great job , very thankful to you

  • @vinaylj
    @vinaylj 12 วันที่ผ่านมา

    I was able to see that curr= prev; mistake as you were typing it. thanks to you Striver. you are the best

  • @ChutHunter
    @ChutHunter 5 หลายเดือนก่อน

    Thank you so much bhaiya, I always heard of this question as one of the most difficult ones. But by following your DP series, I did it on my own. You can easily sell this quality content for ₹ 50k but you're giving it for free. BEST TEACHER EVER ♥♥♥♥

  • @deepurana6010
    @deepurana6010 ปีที่แล้ว +1

    You are amazing ❤️.
    Thanks a lot for this valuable content 🙌🙇🙇

  • @m4n0jkum4r
    @m4n0jkum4r ปีที่แล้ว +1

    In Tabulation we are declaring vector with values zero. So we can skip first two loops.

  • @ranasauravsingh
    @ranasauravsingh 2 ปีที่แล้ว +2

    UNDERSTOOD...
    Thanks striver for the video... :)

  • @kareni7572
    @kareni7572 ปีที่แล้ว +2

    Why can't we put the base case at index 0? Especially for LCS - DP on strings related questions?

  • @avikdey01
    @avikdey01 2 ปีที่แล้ว +6

    In interviews do we need to show the overlapping subproblems by taking longer examples or we can simply move on with memoization?

    • @coding8000
      @coding8000 2 ปีที่แล้ว +3

      take till 5 to 6 steps., if recruiter does want , want he will tell u., to move to next step.

  • @shivamsinghnegi1192
    @shivamsinghnegi1192 ปีที่แล้ว

    Thanks bro the Playlist is top notch...am getting a lot better...Thanks again

  • @Nikhil-ov6sm
    @Nikhil-ov6sm ปีที่แล้ว

    awesome, understood..was pretty easy due to what you've alrready taught

  • @VishalYadav-gk1kg
    @VishalYadav-gk1kg 6 วันที่ผ่านมา +1

    Very nice explanation sir, Thank you!

  • @tibebuwassie6017
    @tibebuwassie6017 ปีที่แล้ว +1

    hey great video but isn't the auxiliary stack space supposed to be max(s.size(), t.size())?

  • @girishbhargava6367
    @girishbhargava6367 2 ปีที่แล้ว

    Striver, why can't we return INT_MIN , in the base case. Because if we return 0, it will be added to 1 and the resultant number will be considered for maximum. And even if it is not the maximum, it will be returned. Your explanation is very intuitive.

  • @sameersahu4569
    @sameersahu4569 2 ปีที่แล้ว

    Loved the Explanation!!Understood

  • @alokbhowmik3547
    @alokbhowmik3547 2 ปีที่แล้ว +1

    what an explanation thanks for your time and such video

  • @rishabhgupta9846
    @rishabhgupta9846 ปีที่แล้ว

    understood,previously I mugged up the tabulation formula for the exam ,but now I know how it came.

  • @DevashishJose
    @DevashishJose 6 หลายเดือนก่อน

    Understood, Thank you so so much.

  • @d_0364
    @d_0364 15 วันที่ผ่านมา

    almost all of the questions in this playlist can be space optimized to not just O(2m) but O(m) if you apply some logic and visualize how the table is being filled.

  • @pj-nz6nm
    @pj-nz6nm ปีที่แล้ว

    hey man i know you are a very good teacher , but you are also a very good human being.

  • @amartyadas5-yriddmechanica597
    @amartyadas5-yriddmechanica597 2 ปีที่แล้ว +1

    Understood. Only one point, if you are doing the tabulation to eliminate the O(m*n) S.C and then including (m+n) extra space for an extra row and column, it seems a bit redundant.

  • @thiyaneswarana3656
    @thiyaneswarana3656 ปีที่แล้ว +2

    hey striver this is regarding ur tuf website......one feedback....can you add another checklist to mark important or tough nut questions so that for revision we can se it carefully again....because this subsequence is screewing up my brain :)

  • @Parmindersingh-of6oo
    @Parmindersingh-of6oo ปีที่แล้ว

    We don't need to add base case while bottom-up in case of index shifting. If we just replace "-1" with "0" while initializing dp vector. Isn't it?

  • @SethuIyer95
    @SethuIyer95 4 หลายเดือนก่อน

    I deeply understand recursion, memoization, tabulation and space optimization.

  • @gyanunlimited740
    @gyanunlimited740 2 ปีที่แล้ว +5

    Man the content is gold.

  • @dashsights4258
    @dashsights4258 ปีที่แล้ว

    Just one word , Beautiful!

  • @HarshSharma-ff3ox
    @HarshSharma-ff3ox 2 ปีที่แล้ว +5

    Thank you Striver for such a wonderful explanation. Finally understood it intuitively. 💯💯

  • @tejasghone5118
    @tejasghone5118 2 ปีที่แล้ว +8

    Can also be done using single array if we preserve cur[j-1] in a prv variable

    • @takeUforward
      @takeUforward  2 ปีที่แล้ว +11

      Yeah.. you guys are learning fast 😍

    • @tejasghone5118
      @tejasghone5118 2 ปีที่แล้ว

      @@takeUforward thanks to your playlist💯

    • @jaykumargupta7307
      @jaykumargupta7307 2 ปีที่แล้ว

      @@tejasghone5118 can u provide the code

    • @himanshuguleria9474
      @himanshuguleria9474 2 ปีที่แล้ว +4

      @@jaykumargupta7307
      int longestCommonSubsequence(string s1, string s2) {
      int n = s1.length(), m = s2.length();
      vector cur(m+1, 0);
      int prev;
      for(int ind1=1; ind1

    • @ishwarshelke128
      @ishwarshelke128 2 ปีที่แล้ว

      can u give the video link in which he taught this space opt technique

  • @oqant0424
    @oqant0424 ปีที่แล้ว

    seriously you are a legit!
    understood ,thanks🙌

  • @coding8000
    @coding8000 ปีที่แล้ว +1

    Again @takeUforwad, just letting you know, again that's stuff you have done, is GOD's own work, thank you for from bottom of my heart, thanks !!!

  • @ritikshandilya7075
    @ritikshandilya7075 28 วันที่ผ่านมา

    Thanks for great explanation striver

  • @varunsharma1889
    @varunsharma1889 2 ปีที่แล้ว

    Very good explanation. Understood. Thanks.

  • @ahsanulanam-4632
    @ahsanulanam-4632 7 หลายเดือนก่อน

    Dhonnobad Brother
    You are great

  • @daniel.w8112
    @daniel.w8112 ปีที่แล้ว

    Thank You Very much Striver !

  • @vijaybhaskar1413
    @vijaybhaskar1413 ปีที่แล้ว

    IN TABULATION WE CAN STORE 0 INTIALLY AND skip the base case loops which is used to store 0 in 0th row and column and same for space optimization

  • @rahulsaha332
    @rahulsaha332 ปีที่แล้ว +2

    Decode ways is a new kind of pattern on dp on strings i think and that can be covered

  • @yashchawla3729
    @yashchawla3729 2 ปีที่แล้ว

    Understood, sir. Thank you very much.

  • @AngadSingh97
    @AngadSingh97 6 วันที่ผ่านมา

    Life Lesson: If Raj tells you to go revise a video, then go revise that video. It's really hard not to understand something once you watch everything in the order he presents.

  • @vishious14
    @vishious14 6 หลายเดือนก่อน

    Was able to solve this on Leetcode by myself. Thanks Striver !!!
    public int longestCommonSubsequence(String s1, String s2) {
    int n1 = s1.length(),n2 = s2.length();
    int[] prev = new int[n2];
    //base cases
    if(s1.charAt(0)==s2.charAt(0)) prev[0]=1;
    for(int i=1;i

  • @sanyazaveri4511
    @sanyazaveri4511 ปีที่แล้ว

    Awesome lecture. Understood!

  • @user-oi6eb7ru2s
    @user-oi6eb7ru2s 8 หลายเดือนก่อน

    Thanks a lot striver

  • @himanshugoyal7941
    @himanshugoyal7941 ปีที่แล้ว +1

    Can anyone please explain why (index1 == 0 || index2 == 0) has not been considered as base case here as we did in DP of arrays?
    In DP of Arrays, I was trying to use (index < 0) as the base case, but when I saw Striver's video, I changed my approach to his, where he was considering (index == 0 ) as the base case. But now, in this, he is using the other way around.
    Can someone please explain why?

    • @sanyattaneja8551
      @sanyattaneja8551 ปีที่แล้ว +1

      You can use index1 == 0 || index2 == 0 but then it will have 2 cases 1) if(index1 == 0 && index2 == 0) return s1[index1] == s2[index2] ;
      2) if(index1 == 0 || index2 == 0) \\ using loop find the single character(having index == 0) in other string if present return 1 else return 0
      therefore it is difficult to find and index < 0 base case is much easier so it's better to write that

  • @ganeshkamath89
    @ganeshkamath89 2 ปีที่แล้ว

    Thanks Striver. Understood LCS.

  • @rakshitpandey7517
    @rakshitpandey7517 2 ปีที่แล้ว +3

    Without right shifting the Indexes, still we could do it as default initialise with 0 and then start from i=0 and j=0 but adding constraints of out of bounds.
    #include
    //Tabulation Solution
    int lcs(string s, string t)
    {
    int n1=s.size();
    int n2=t.size();
    vectordp(n1,vector(n2,0));

    for(int i=0;i=0){
    dp[i][j]=1+dp[i-1][j-1];
    }
    else{
    dp[i][j]=1;
    }
    }
    else{
    int a=0,b=0;
    if(i-1>=0){
    a=dp[i-1][j];
    }
    if(j-1>=0){
    b=dp[i][j-1];
    }
    dp[i][j]=max(a,b);
    }
    }
    }
    return dp[n1-1][n2-1];


    //Write your code here
    }

    • @NarenderMajoka
      @NarenderMajoka 2 ปีที่แล้ว

      I did the same with java code

  • @rpriyanka28
    @rpriyanka28 3 หลายเดือนก่อน +1

    he is the example of beauty with brains

  • @veereshr
    @veereshr 2 ปีที่แล้ว +33

    Does interviewers expect us to know the tabulation directly? because I can solve tabulation only after analysing recursion

    • @viasmit
      @viasmit 2 ปีที่แล้ว +11

      No, Its not expected to directly jump to the tabulation. In Contrast, the interviewer will rather be impressed, that you moved your solution trom recursion to memoised to space optimised solution

    • @parthsalat
      @parthsalat 2 ปีที่แล้ว +4

      @@viasmit Exactly, they want to know how we reach the tabulation from the recursion

    • @divyanshsharma8401
      @divyanshsharma8401 ปีที่แล้ว +2

      @@parthsalat is space optimization after tabulation essential?

    • @parthsalat
      @parthsalat ปีที่แล้ว +6

      @@divyanshsharma8401 An average interview question lasts around 45 mins. If you have time remaining, then yes, go for space optimisation.
      But it isn't compulsory.

  • @prabhakaran5542
    @prabhakaran5542 4 หลายเดือนก่อน +1

    Understood ❤

  • @AbdulKadir-bh3el
    @AbdulKadir-bh3el 2 ปีที่แล้ว

    understood bruh, plz make video on sliding window technique too.

  • @md.rashedulislam5141
    @md.rashedulislam5141 2 ปีที่แล้ว +1

    Is it possible to represent every dp problem by recursion tree?

  • @abdallaalhag4425
    @abdallaalhag4425 7 หลายเดือนก่อน

    Understood boss man!

  • @priyanshuchouhan9845
    @priyanshuchouhan9845 10 หลายเดือนก่อน +3

    who agrees that this dp series is one of the best on TH-cam

    • @tasneemayham974
      @tasneemayham974 9 หลายเดือนก่อน

      Not one of the best no. THE BESTTTTT!!!!!

  • @jarvis3551
    @jarvis3551 7 หลายเดือนก่อน

    did it in 1st attempt without seeing the video, shifting index to right was new to me

  • @harisai3580
    @harisai3580 6 หลายเดือนก่อน

    Understood Sir!

  • @user-ke7fs7ds6h
    @user-ke7fs7ds6h 6 หลายเดือนก่อน

    GOAT for a reason❤❤

  • @Harshanandita
    @Harshanandita ปีที่แล้ว +1

    Today, I solved my first ever dp problem in a contest just by watching this video...
    Codechef Starter 71 Longest Common Subsequence problem

  • @jaideeppyne1880
    @jaideeppyne1880 ปีที่แล้ว

    very well explained step by step

  • @sangharshpipare666
    @sangharshpipare666 หลายเดือนก่อน

    In case of Java while doing the space optimization when we reassign prev = current; why do we require to clone it? It was working when we were simply assigning the last time.
    Edit: I think I was creating current array inside the first for loop and thus it didn't require cloning.

  • @karansoni1660
    @karansoni1660 ปีที่แล้ว

    Length of both the String can be different, how the o(N) space solution will work for this?

  • @krishanpratap3286
    @krishanpratap3286 2 ปีที่แล้ว

    In this qye shifting humne khali comparsion wale usme kyon kia hain like wile function call humko I ko i-1 se replace nahi karna?

  • @raZer.7_7
    @raZer.7_7 2 วันที่ผ่านมา

    UNDERSTOOD!

  • @hemanthkumar516
    @hemanthkumar516 10 หลายเดือนก่อน

    in tabulation method to avoid getting negative values this condition can be used
    if(i1==0 || i2==0){
    if(s1.charAt(i1)==s2.charAt(i2)){
    dp[i1][i2]=1;}
    else if(i1==0 && i2!=0){
    dp[i1][i2]=dp[i1][i2-1];}
    else if(i1!=0 && i2==0){
    dp[i1][i2]=dp[i1-1][i2];
    }
    }

  • @santoshb7776
    @santoshb7776 7 หลายเดือนก่อน

    Understood sir ! 🙏🙏

  • @jskr456
    @jskr456 7 หลายเดือนก่อน

    very good explanation

  • @honeykumar5700
    @honeykumar5700 2 ปีที่แล้ว +1

    i myself did it 1array space optimisation ! quite impressive how i learnt that fast 😀😀

    • @justarandomguy6106
      @justarandomguy6106 ปีที่แล้ว

      can you please share the code of 1 array optimisation , my 1 array code giving me wrong answer on leetcode testcase 23 , i saw a solution where someone uses 2 extra variables to do in 1 array. plz reply

  • @zodiacsama7693
    @zodiacsama7693 ปีที่แล้ว

    how we computed the time complexity of recursive solution?

  • @jitendrasinghsola
    @jitendrasinghsola 2 ปีที่แล้ว +3

    I was always scared of these LCS and all but not anymore thanks to striver

  • @HarchitGulati
    @HarchitGulati ปีที่แล้ว +1

    Bhaiya ,why cant we solve this question like if we have got two strings then we are eliminating the characters from both strings that are uncommon and dont have frequency 1 (checking that in common characters)..ultimately we will get two resultant strings and if they are equal that is longest subsequence and if not there is no longest common subsequence present ..pls clear my doubt

  • @Sumeet_100
    @Sumeet_100 หลายเดือนก่อน +1

    Understood !!

  • @jashhinger442
    @jashhinger442 ปีที่แล้ว

    Love the concept ✨