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

Поділитися
Вставка
  • Опубліковано 22 лис 2024
  • Lecture Notes/C++/Java Codes: takeuforward.o...
    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/take...
    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.o...
    You can also get in touch with me at my social handles: linktr.ee/take...

КОМЕНТАРІ • 872

  • @pratyakshsinha6292
    @pratyakshsinha6292 2 роки тому +196

    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 Рік тому +22

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

    • @iamnoob7593
      @iamnoob7593 10 місяців тому +1

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

    • @idris110
      @idris110 10 місяців тому +5

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

    • @bharatravihal9646
      @bharatravihal9646 10 місяців тому

      🤣🤣@@idris110

    • @spoidy2025
      @spoidy2025 8 місяців тому

      brother are you placed

  • @anweshabanerjee6241
    @anweshabanerjee6241 2 роки тому +84

    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😁

  • @art4eigen93
    @art4eigen93 2 роки тому +205

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

    • @wahtNIGGA
      @wahtNIGGA 9 місяців тому +2

      Yes he is GOAT
      I am the future

    • @abhishekkarn8918
      @abhishekkarn8918 7 місяців тому +2

      He is already for me.

    • @v7gamerff809
      @v7gamerff809 3 місяці тому

      No a Guy named Srikar From Vizag will go down as the GOAT online DSA in future

    • @madhu_mohanreddy
      @madhu_mohanreddy 2 місяці тому

      @@v7gamerff809as usual, just a dumb guy from ap.

    • @Alex-ue9du
      @Alex-ue9du 10 днів тому

      True

  • @arjundevmishra7207
    @arjundevmishra7207 Рік тому +64

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

  • @arunkumarsahoo1344
    @arunkumarsahoo1344 2 роки тому +26

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

  • @manthenanagendra1077
    @manthenanagendra1077 2 роки тому +132

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

  • @sujalgupta6100
    @sujalgupta6100 2 роки тому +76

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

    • @dikshamakkar2850
      @dikshamakkar2850 3 місяці тому

      Loop is required in C++ to initialize array with 0s. But for Java it is not required as by default array is declared with 0s.

    • @vizzz8906
      @vizzz8906 3 місяці тому

      @@dikshamakkar2850 I have a question , vector dp(n + 1, vector(m + 1,0)); this line of code initializes all index to 0 then why did he ran 2 more loops to initialize some row and column to 0 again?

    • @madhu_mohanreddy
      @madhu_mohanreddy 2 місяці тому

      @@dikshamakkar2850 nah loop isnt required
      class Solution {
      public:
      int longestCommonSubsequence(string text1, string text2) {
      int n = text1.size();
      int m = text2.size();
      vectorprev(m+1,0),curr(m+1,0);
      for(int i=1;i

    • @gomzysharma
      @gomzysharma 2 місяці тому +2

      you're right but that's write for clarity purpose that how we are generating tabulation from already written memorization solution

    • @himanshukandwal8710
      @himanshukandwal8710 Місяць тому +1

      @@vizzz8906 he forgot to remove this loop.

  • @donno2423
    @donno2423 Рік тому +14

    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.

  • @duyhuynh1234
    @duyhuynh1234 Рік тому +8

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

  • @varunbansal1136
    @varunbansal1136 Рік тому +5

    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.

  • @kartiksuman9814
    @kartiksuman9814 2 роки тому +58

    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

  • @sahitid5570
    @sahitid5570 12 днів тому

    Understood!! I don't think any other explanation video can match this one. You are God sent!!

  • @kanikajain5627
    @kanikajain5627 4 місяці тому

    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.

  • @avimandavia6154
    @avimandavia6154 Рік тому +6

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

  • @Amitchoudhary-ij4we
    @Amitchoudhary-ij4we 2 роки тому +14

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

  • @shuvbhowmickbestin
    @shuvbhowmickbestin 29 днів тому

    What a brilliant explanation, I come here after watching Aditya Verma's videos on DP but didn't feel the intuition behind the tabulation that he was doing and now I know the thought process all thanks to Striver.

  • @akashyadagouda896
    @akashyadagouda896 10 місяців тому +1

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

  • @mrcamara5574
    @mrcamara5574 Місяць тому

    Honestly, everytime i listen to you dude i feel like i can handle anything ! much love from Paris

  • @therangeplus
    @therangeplus 12 годин тому

    best explanation I have received ever. U are the best. Im watch this whole playlist to prep for my interviews

  • @ramanahlawat398
    @ramanahlawat398 Рік тому +4

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

  • @siddharthsarraf330
    @siddharthsarraf330 2 роки тому +7

    for those who don' t want to use shifting of index in tabulation , they can do it in traditional way using below code. we can discuss if you have any doubts.
    int longestCommonSubsequence(string text1, string text2) {
    int n1= text1.size();
    int n2= text2.size();
    vector dp(n1, vector(n2, -1));

    //filling first coloumn of the matrix
    //say we have text1= bcade and text2=a then
    //the longest cmmn subsqnce is 0 until index1 reaches 2, once it reaches 2 beyond that lcs =1;


    for(int i=0; i

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

  • @vedxnt10
    @vedxnt10 6 місяців тому

    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

  • @arnabroy2995
    @arnabroy2995 Рік тому +4

    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❤

  • @stith_pragya
    @stith_pragya 10 місяців тому +1

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

  • @vamsikrishnareddy9345
    @vamsikrishnareddy9345 4 місяці тому

    Understood!!!
    Same tabulation method that you taught in previous videos... Same approach without index shifting.
    Base case in Memoization :
    if(index1 == 0 || index2 == 0) {
    return s1.charAt(index1) == s2.charAt(index2) ? 1 : 0;
    }
    Tabulation :
    static int tabulation(int index1, int index2, String s1, String s2) {
    int[][] dp = new int[s1.length()][s2.length()];
    dp[0][0] = s1.charAt(0) == s2.charAt(0) ? 1 : 0;
    for(int i = 1; i

  • @virgarg1012
    @virgarg1012 5 місяців тому +1

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

  • @deadlockgaming8553
    @deadlockgaming8553 2 місяці тому +1

    you are a god level teacher🙇‍♂🙇‍♂🙇‍♂
    never thought dp would be so easy

  • @sarveshamrute4982
    @sarveshamrute4982 2 роки тому +7

    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

  • @ankita716
    @ankita716 5 місяців тому +1

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

  • @m4n0jkum4r
    @m4n0jkum4r 2 роки тому +1

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

  • @priyanshuchouhan9845
    @priyanshuchouhan9845 Рік тому +4

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

  • @vinaylj
    @vinaylj 4 місяці тому

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

  • @vaibhavrawat4008
    @vaibhavrawat4008 2 місяці тому

    most in depth explanation, thanks

  • @neilbohr6015
    @neilbohr6015 25 днів тому

    if someone doesn't want shifting they can write base case as below
    idea is to make let say dp[0][i1]=1 and also all further i>i1 equal to 1 eg dp[0][i1+1]=1,dp[0][i1+2]=1,....
    similarly for second loop also
    remember what dp[i][j] represents: ;length of lcs of substring s1[0...i] and s2[0..j]
    bool b=false;
    for(int i=0;i

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

  • @nottheradbrad184
    @nottheradbrad184 Рік тому

    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❤

  • @VishalYadav-gk1kg
    @VishalYadav-gk1kg 4 місяці тому +1

    Very nice explanation sir, Thank you!

  • @mahammedhashish9170
    @mahammedhashish9170 Рік тому +1

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

  • @tejasghone5118
    @tejasghone5118 2 роки тому +8

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

    • @takeUforward
      @takeUforward  2 роки тому +13

      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

  • @yashsinghal3404
    @yashsinghal3404 2 роки тому +5

    What an easy explanation, loved it !

  • @SethuIyer95
    @SethuIyer95 8 місяців тому

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

  • @rpriyanka28
    @rpriyanka28 7 місяців тому +1

    he is the example of beauty with brains

  • @raghavmanish24
    @raghavmanish24 3 місяці тому

    understood .....thanku striver .....let's finish this dp on string topic

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

  • @NiharIngale
    @NiharIngale 3 місяці тому

    If you started new topic like DP on string it is important that you should explain each problem with tabulation method also thoroughly, instead of just writing code, but Great Series.

  • @charan775
    @charan775 2 місяці тому

    pro tip -> use right shift method in all questions instead of using index. this way its way easier to write base cases, because you can clearly call out whats the answer when length of array is 0

    • @namanpaliwal4858
      @namanpaliwal4858 Місяць тому

      I didn't get it could you please explain a lil bit.

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

  • @mohammedraiyaan-bt6iy
    @mohammedraiyaan-bt6iy Місяць тому

    Amazing lecture sir ❤❤❤.
    Thanks for all your efforts for us.

  • @gyanunlimited740
    @gyanunlimited740 2 роки тому +5

    Man the content is gold.

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

  • @dharanyuvi6951
    @dharanyuvi6951 4 місяці тому

    Believe or not Striver
    I solved the problem by myself without seeing this video
    Note : I gone through all your previous dp videos properly with no skip :)
    I am so happy.. Thanks to you.

  • @Anmol-h8z
    @Anmol-h8z 6 днів тому +1

    Understood very well

  • @World-Of-Mr-Motivater
    @World-Of-Mr-Motivater 4 місяці тому +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!!

  • @BG-lj6fw
    @BG-lj6fw Рік тому

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

  • @rishabhgupta9846
    @rishabhgupta9846 Рік тому

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

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

  • @hashcodez757
    @hashcodez757 3 місяці тому

    "UNDERSTOOD BHAIYA!!"

  • @abhinavgoli868
    @abhinavgoli868 4 місяці тому +1

    when the character was not matching why are we not considering the possiblity of f(index1-1,index2-1). Thanks for the help

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

  • @ntgrn-pr5yx
    @ntgrn-pr5yx 25 днів тому

    understood thank you Striver

  • @d_0364
    @d_0364 4 місяці тому

    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.

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

  • @jarvis3551
    @jarvis3551 11 місяців тому

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

  • @pj-nz6nm
    @pj-nz6nm Рік тому

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

  • @chandbasha8684
    @chandbasha8684 Місяць тому

    It would be helpful if you explain optimal structure of the problem with a concrete proof

  • @vishious14
    @vishious14 11 місяців тому

    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

  • @adityabodkhe914
    @adityabodkhe914 Рік тому +1

    Hi Raj the whole video was very explanative ,but the last space optimization part was not clear to me as why the prev and curr array has to be of size m and not n

    • @VishalGupta-xw2rp
      @VishalGupta-xw2rp Рік тому

      Because as in Space Optimization we required only Columns not Rows....
      n rows
      m cols
      So both the vectors were of size m i.e, Columns

  • @prabhakaran5542
    @prabhakaran5542 8 місяців тому +1

    Understood ❤

  • @ahsanulanam-4632
    @ahsanulanam-4632 11 місяців тому

    Dhonnobad Brother
    You are great

  • @ritikshandilya7075
    @ritikshandilya7075 5 місяців тому

    Thanks for great explanation striver

  • @meetharsoda5152
    @meetharsoda5152 5 місяців тому +1

    Finally DP on strings Let's Go

  • @gouravkumar7459
    @gouravkumar7459 2 роки тому +1

    you forgot to update the description box. 😊

  • @adarshanku7988
    @adarshanku7988 2 роки тому +2

    Understood..! Awesome method "shifting of index" 😁......though without shifting i have solved tabulation, all credits to you only, but shifting of index makes that too easy. Love you ❤

  • @harshitatripathi6440
    @harshitatripathi6440 Рік тому

    best dp playlist on youtube

  • @kareni7572
    @kareni7572 Рік тому +2

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

  • @dashsights4258
    @dashsights4258 Рік тому

    Just one word , Beautiful!

  • @AmanKumar-qz4jz
    @AmanKumar-qz4jz 10 місяців тому

    god!!! of teaching dsa
    understood

  • @rohan8758
    @rohan8758 5 місяців тому +1

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

  • @tbt4283
    @tbt4283 Рік тому

    You always have very good solutions, but your writing is hard for us to clearly get all information, I think we should write upper case for all letters, then it will be helpful for all. Thank you

  • @DevashishJose
    @DevashishJose 10 місяців тому

    Understood, Thank you so so much.

  • @ABDULRAHMAN-hr3ko
    @ABDULRAHMAN-hr3ko 3 місяці тому

    thanks for beautiful explanation

  • @sypher4735
    @sypher4735 2 роки тому +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😂

  • @biswajitadhikary_0807
    @biswajitadhikary_0807 2 місяці тому

    Understand it very clearly>>

  • @harihardhik3293
    @harihardhik3293 3 місяці тому

    Understood sir very well!!

  • @HIMANSHU-u6y
    @HIMANSHU-u6y 3 місяці тому

    Striver what do u eat, how can be someone explain in such an excellenct manner❤

  • @shauryatomer1058
    @shauryatomer1058 Місяць тому

    Once again thanks for this awesome content

  • @jitendrasinghsola
    @jitendrasinghsola 2 роки тому +3

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

  • @striverdaaadi
    @striverdaaadi 11 місяців тому

    GOAT for a reason❤❤

  • @UECAshutoshKumar
    @UECAshutoshKumar 5 місяців тому +1

    Thank You
    Understood!!!

  • @ranasauravsingh
    @ranasauravsingh 2 роки тому +2

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

  • @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 :)

  • @HarshSharma-ff3ox
    @HarshSharma-ff3ox 2 роки тому +5

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

  • @NaveenPGForYou
    @NaveenPGForYou Місяць тому

    You are a rockstar.. loved it

  • @iamnoob7593
    @iamnoob7593 10 місяців тому

    US Striver , Getting into Google i can image ur DSA level 🔥

  • @rahulsaha332
    @rahulsaha332 2 роки тому +2

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

  • @shivamsinghnegi1192
    @shivamsinghnegi1192 Рік тому

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

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

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

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