DP 27. Longest Common Substring | DP on Strings 🔥

Поділитися
Вставка
  • Опубліковано 26 сер 2024
  • Lecture Notes/C++/Java Codes: takeuforward.o...
    Problem Link: bit.ly/3H2M3KS
    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 MCM Dp, this is the first problem on the pattern Partition 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...

КОМЕНТАРІ • 455

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

    Amazing explanation brother. if anyone is confused about why we are taking dp[i][j] = 0, note that dp[i][j] here indicates the length of longest substring ending at index i of the s1 and index j of s2 string.

    • @subasishkar9469
      @subasishkar9469 2 роки тому

      I am not getting the mismatch condition only please can you elaborate

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

      ha bhai thank you 😂

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

      right I needed to confirm with someone

    • @jayantmishra2266
      @jayantmishra2266 Рік тому +3

      Small Correction : note that dp[i][j] here indicates the length of longest substring ending at index i-1 of the s1 and index j-1 of s2 string, cause here i and j refers to length of s1 and s2 respectively, so access last char of s1 and s2 we'll do s1[i-1] and s2[j-1].

    • @SohailKhan-cx9gb
      @SohailKhan-cx9gb 11 місяців тому +1

      ​@@jayantmishra2266yes bro because in tabulation we cannot write the negative condition so we have shifted i-1 to i

  • @user-fy4uq4lw8l
    @user-fy4uq4lw8l 8 місяців тому +11

    Just pointed out
    We can ignore the base case and else condition . it still works as the dp array is initially filled with with zero only.
    So no need to again assign 0 to it.

  • @chandanbera2692
    @chandanbera2692 2 роки тому +11

    Recursion solution
    static int lcs(int m, int n, String s1, String s2, int count) {
    if(m

  • @divyendragahlot9231
    @divyendragahlot9231 2 роки тому +65

    You should have told the recursive approach too. You had done that in all the previous videos.

    • @vikasbelida3218
      @vikasbelida3218 Рік тому +16

      here's the recursive solution:
      public int lcs(int[] A, int[] B, int m, int n, int res) {
      if (m == -1 || n == -1) {
      return res;
      }
      if (A[m] == B[n]) {
      res = lcs(A, B, m - 1, n - 1, res + 1);
      }
      return max(res, max(lcs(A, B, m, n - 1, 0), lcs(A, B, m - 1, n, 0)));
      }

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

      @@vikasbelida3218 can you share memoization one also ,I'm not able to do it

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

      @@allideas777 res is also changing so that also needs to be considered in dp table,so there are 3 parameters
      therefore 3D array is needed.

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

      Only real programmers can do that because you won't find recursive approach at most of the places. Most of these youtubers understand the omnipresent solution and explain it here with a few additions here and there.

    • @av21015
      @av21015 Рік тому +3

      @@datahacker1405 is it even possible to solve this using memoization? I tried but couldn't

  • @tawhidjoarder756
    @tawhidjoarder756 2 роки тому +35

    This guy really deserves a medal.

  • @himanshuagrawal8012
    @himanshuagrawal8012 2 роки тому +50

    #UNDERSTOOD Bhaiya...I am now able to develop logic before watching the video...still I watch video after submitting just to go through once and to see your energy level...🙂🙂😍😍

  • @shaileshsingh6771
    @shaileshsingh6771 Рік тому +7

    We can space optimize it to 1D array:-
    int findLength(vector& nums1, vector& nums2) {
    int n = nums1.size(), m = nums2.size();
    int maxLength = 0;
    vector prev(m+1,0);
    for(int i=1; i0; j--) {
    if(nums1[i-1] == nums2[j-1]) {
    prev[j] = 1 + prev[j-1];
    maxLength = max(maxLength,prev[j]);
    }
    else prev[j] = 0;
    }
    }
    return maxLength;
    }

  • @rossgeller9372
    @rossgeller9372 Рік тому +61

    if anyone wants a recursive approach for this, here it is->
    src:
    int lcsHelper(string &str1, string &str2, int n, int m, int count){
    if (m == -1 || n == -1){
    return count;
    }
    if (str1[n] == str2[m]){
    count = lcsHelper(str1, str2, n - 1, m - 1, count + 1);
    }
    count = max({count, lcsHelper(str1, str2, n - 1, m, 0), lcsHelper(str1, str2, n, m - 1, 0)});
    return count;
    }
    int lcs(string &str1, string &str2){
    return lcsHelper(str1, str2, str1.length() - 1, str2.length() - 1, 0);
    }

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

      why this memoization code gives wrng ans-//{ Driver Code Starts
      #include
      using namespace std;
      // } Driver Code Ends
      class Solution{
      public:
      int dp[1001][1001];
      int solve(string S1,string S2,int n,int m,int cnt){
      if(n==-1||m==-1)return cnt;
      if(dp[n][m]!=-1)return dp[n][m];
      if(S1[n]==S2[m]){ cnt= solve(S1,S2,n-1,m-1,cnt+1);}
      else{
      cnt= max({cnt,solve(S1,S2,n-1,m,0),solve(S1,S2,n,m-1,0)});
      }
      return dp[n][m]=cnt;
      }
      int longestCommonSubstr (string S1, string S2, int n, int m)
      { memset(dp,-1,sizeof(dp));
      int cnt=0;
      return solve(S1,S2,n-1,m-1,0);
      }
      };
      //{ Driver Code Starts.
      int main()
      {
      int t; cin >> t;
      while (t--)
      {
      int n, m; cin >> n >> m;
      string s1, s2;
      cin >> s1 >> s2;
      Solution ob;
      cout

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

      mr geller i thought you were a paleontologist

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

      @@riteshmohan3454 yeah i also thought he's a polontologist

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

      memoization is not work on this

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

      @@ravindrayadav6103 not working on these TC
      1)yxyy
      yxy
      ans->3
      2)yxxzzxxxx
      yzyzxxyxxz
      ans->4

  • @sanginigupta1312
    @sanginigupta1312 2 роки тому +17

    Here, arr[i][j] can mean the longest substring that ends at ith character in string 1 and at jth character in string 2, and we take the max of all the combinations!

  • @raghavmanish24
    @raghavmanish24 9 днів тому

    this question like one of the easiest question after following your videos....thanku striver

  • @parthib_deb23
    @parthib_deb23 2 дні тому

    make a well-built hashmap and check within it. Its possible to do in O(N) time.
    There is a simple reason behind it - In subsequence the order of words doesnot matter which makes the solution prone to more edgecases but in substring , even if there is one single character unmatched you can't go forward

  • @wrongnotes1157
    @wrongnotes1157 Рік тому +11

    here is the memorization method:
    int lcsUtil(string& s1, string& s2, int n, int m, vector& dp) {
    if (n == 0 || m == 0) {
    return 0;
    }
    if (dp[n][m] != -1) {
    return dp[n][m];
    }
    int result = 0;
    if (s1[n-1] == s2[m-1]) {
    result = 1 + lcsUtil(s1, s2, n-1, m-1, dp);
    }
    else {
    result = 0;
    }
    dp[n][m] = result;
    return result;
    }
    int lcs(string& s1, string& s2) {
    int n = s1.size();
    int m = s2.size();
    vector dp(n+1, vector(m+1, -1));
    int ans = 0;
    for (int i = 1; i

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

      nice brother this is working

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

      how is it different from the brute force as this also has TC O(n^3) ans the TC of brute force id also O(n^3)

    • @SohailKhan-cx9gb
      @SohailKhan-cx9gb 11 місяців тому

      Same bro 🤜

  • @gsampath8017
    @gsampath8017 2 роки тому +29

    from where have you learned dsa ?? if you have not understood a specific topic how to handle it??

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

      search is the only solution go n search

  • @dadidivya8663
    @dadidivya8663 Рік тому +36

    Just in case if anyone needs recursive approach for this:
    Recursive code:
    def lcs(s, t) :
    def solve(i1,i2):
    if(i1

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

      best

    • @KunalJaiswal-og7nf
      @KunalJaiswal-og7nf Рік тому

      @@ScrollWthMahadev can convert to c++??

    • @sharmaanuj334
      @sharmaanuj334 Рік тому +3

      Hey, I am not able to understand why you have done nomatch = min(solve(), solve(), 0) since it would always give 0 for nomatch

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

      same question@@sharmaanuj334

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

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

  • @ShubhamVerma-hw4uj
    @ShubhamVerma-hw4uj 2 роки тому +22

    for those who want to solve this question on leetcode, it is lc 718

  • @munnakrish3572
    @munnakrish3572 2 роки тому +6

    understood!..Thanks for explaining this in an elegant way!

  • @nitin50056
    @nitin50056 2 роки тому +6

    Can you share a memoization solution ?

  • @shuvbhowmickbestin
    @shuvbhowmickbestin 21 день тому

    is there a reason why we're not talking about the memoization approach here? I kinda know the answer but it'd be better if the memoization approach is also discussed or told why it is not being considered for this problem because we always go from recursion to memoization to tabulation. This is the right approach for solving DP problems.

  • @harshitsen5479
    @harshitsen5479 11 місяців тому +3

    In the no-matching condition in the case of subsequence we were basically skipping one element from the str1 in the first recursion call and one element from the str2 in the second recursion call (since subsequence can be or cannot be continous), but in the case of substring we cannot skip an element to form a substring (as it must be continous). So that's why we returned 0 straight away.

  • @parthib_deb23
    @parthib_deb23 2 дні тому

    class Solution:
    def findLength(self, nums1: list[str], nums2: list[str]) -> int:
    if nums1==nums2:
    print(len(nums1))
    elif nums1==[] or nums2==[]:
    print(0)
    elif nums1==nums2[::-1]:
    count=1
    for i in range(1,len(nums1)):
    if nums1[i]==nums1[i-1]:
    count+=1
    return count
    else:
    map={nums1[i]:set() for i in range(len(nums1))}
    map[nums1[0]].add(nums1[0])
    for i in range(1,len(nums1)):
    map[nums1[i]].add(nums1[i-1])
    print(map)
    temp_iter=[]
    temp=0
    final=[]
    count=0
    for i in range(len(nums2)):
    if nums2[i] in map.keys():
    if temp==0:
    temp=1
    else:
    if nums2[i-1] in map[nums1[i]]:
    if nums2[i-1] not in temp_iter:
    temp_iter.append(nums2[i-1])
    temp_iter.append(nums2[i])
    temp+=1
    else:
    if temp>count:
    final=temp_iter
    count=temp
    temp=0
    temp_iter=[]
    return count
    print(Solution().findLength(['1','2','3','2','1'],['3','2','1','4','7']))
    print(Solution().findLength(['0','0',1],['1','0','0']))
    this is the approach

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

    Striver, Please make a video on how to print Longest Palindromic Substring, because reversing the string technique won't work like we did for Longest Palindromic Subsequence.

    • @papayasprout
      @papayasprout 2 роки тому

      Why will it not work?

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

      @@papayasprout Because this approach will fails when there exists a reversed copy of a non-palindromic substring in some other part of our original string. Ex - "aacdacaa"

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

      @@lokeshdohare2579 i am facing the same problem, did u come up with any modification over striver's code

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

      @@omkumarsingh4194 I came up with a solution, but that's not a dp solution.

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

      @@lokeshdohare4872 alright, can u share that. Btw I solved using same dp by striver . Just introduced one condition when u are updating ans that is
      I-dp[I][j] == n-j. Means we are checking whether startpoint of both substrings is same

  • @vinaykumar9002
    @vinaykumar9002 Рік тому +23

    Equivalent leetcode question for this is "718. Maximum Length of Repeated Subarray "

  • @vikasbelida3218
    @vikasbelida3218 Рік тому +3

    incase anyone looking for recursive solution:
    public int lcs(int[] A, int[] B, int m, int n, int res) {
    if (m == -1 || n == -1) {
    return res;
    }
    if (A[m] == B[n]) {
    res = lcs(A, B, m - 1, n - 1, res + 1);
    }
    return max(res, max(lcs(A, B, m, n - 1, 0), lcs(A, B, m - 1, n, 0)));
    }

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

    here is the recursive & memoization approach..........
    // recursive
    int func(int ind1,int ind2,string &s1,string &s2,int &ans){
    if(ind1

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

      Bhai aapka memoization ka code toh pura recursive hai, joh aapne dp[][] array pass krri hai uska kuch use hi nhi hai
      recursive code shi lga 🙂

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

      @@anshumaan1024 you are correct bro, return dp[ind1][ind2]=match ;
      now,it will be working fine ,thanks

    • @kushalgupta2041
      @kushalgupta2041 5 днів тому

      @@maradanikhil6882 na bro it will give you wrong answer try it and even if you want to do it recursive way the time complexity will be like brute force

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

    UNDERSTOOD, Striver Bhaiya!
    Here's Another Brute force method WITHOUT USING DP:
    int lcs(string &str1, string &str2){
    int n = str1.size(), m = str2.size(), maxLen = 0;
    for(int i = 0; i < n; i++) {
    for(int j = 0; j < m; j++) {
    if(str1[i] == str2[j]){
    int ptr1 = i, ptr2 = j;
    int currLen = 0;
    while(ptr1 < n && ptr2 < m && str1[ptr1] == str2[ptr2]){
    currLen++;
    ptr1++, ptr2++;
    }
    maxLen = max(maxLen, currLen);
    }
    }
    }
    return maxLen;
    }

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

    Striver sir, this problem can also be solved by using just one array by traversing from the back:
    import java.util.*;
    public class Solution
    {
    public static int lcs(String str1, String str2) {
    int n1 = str1.length();
    int n2 = str2.length();
    int prev[] = new int[n2+1];
    int ans = 0;
    for(int i=1; i0; j--)
    {
    if(str1.charAt(i-1)==str2.charAt(j-1))
    {
    prev[j] = 1 + prev[j-1];
    }
    else
    {
    prev[j] = 0;
    }
    ans = Math.max(ans, prev[j]);
    }
    }
    return ans;
    }
    }

    • @harshjain8823
      @harshjain8823 2 роки тому

      How its working ?
      what is the intuition ..

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

      @@harshjain8823 it's just 1d conversion of 2 individual 1d ..and for curr in matching condition curr[index2]= prev[index2-1]...so u just nedd prev[index2-1] so...u can rewrite on prev array itself from n2 to 0 because for current index u only need value of just previous index..so u can easily rewrite it..

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

    Understood ❤

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

    Understood !!
    Thank You, for your hard work..

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

    UNDERSTOOOD UNDERSTOOOD UNDERSTOOOD!!!
    BEST TEACHERRRR EVERRRRR!!!!!!!!💯💯💯💯

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

    UNDERSTOOD...!!
    Thank you striver for the video... :)

  • @googleit2490
    @googleit2490 9 місяців тому

    Done and dusted in the revision session :)
    Nov'14, 2023 04:37 pm

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

    Thank You
    Understood!!!

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

    How are ppl coming with such simple solutions

  • @fanofabdevillersandmathslo5960

    understood

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

    1-Array space optimised solution.
    int lcs(string &s1, string &s2){
    int len1 = s1.length(), len2 = s2.length();
    vector state(len2+1);
    int prev = 0;
    int temp, res = 0;
    for(int i=1; i

  • @aakashbhandari9761
    @aakashbhandari9761 9 місяців тому

    Sir understood Well! , But just want to ask is the below code is right ?
    String a="aakabdqwer";
    String b="abkasxgdqwer";
    int i=a.length()-1;
    int j=b.length()-1;
    int count=0;
    int ans=0;
    while(i>= 0 && j>= 0){
    if(a.charAt(i)==b.charAt(j)){
    count ++;
    i--;
    j--;
    }else{
    count=0;
    i--;
    j--;
    }
    ans=Math.max(count,ans);
    }
    System.out.println(ans);

  • @uday_berad
    @uday_berad 6 місяців тому +1

    // memoization in C++
    class Solution {
    vector dp;
    public:
    int rec(int i,int j,vector& nums1, vector& nums2,int &ans){
    if(i

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

    using recursion c++
    #include
    int solve(int n, int m, string &s1, string &s2, int count){
    if(n == 0 || m == 0){
    return count;
    }
    if(s1[n-1]==s2[m-1]){
    count = solve(n-1, m-1, s1, s2, count+1);
    }
    int count2 = solve(n, m-1, s1, s2, 0);
    int count3 = solve(n-1, m, s1, s2, 0);
    return max(count, max(count2, count3));
    }
    int lcs(string &str1, string &str2){
    return solve(str1.length(), str2.length(), str1, str2, 0);
    }

  • @sparshyadav9709
    @sparshyadav9709 22 дні тому

    Understood.

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

    Thanks for great solution Striver

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

    I got the intuition within 4mins of you video.😎😎

  • @animeshkumar2683
    @animeshkumar2683 9 днів тому

    Understood

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

    understood :)❤ still we can optimise this to one array by a loop m to 1

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

    so here dp[i][j] indicates that longest common substring in which s1[i] and s2[j] are matching?

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

    understood.

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

    Printing the LCS:
    #include
    using namespace std;
    int main()
    {
    string s1,s2;
    cin>>s1>>s2;
    int n= s1.size();
    int m = s2.size();
    vectordp(n+1,vector(m,0));
    int res = 0;
    int startIdx = -1, endIdx = -1;
    int st = INT_MAX;
    for(int i=1;i

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

    Understood!

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

    code for printing longest common substring
    #include
    using namespace std;
    void lcs(string str1, string str2) {
    int n =str1.size();
    int m= str1.size();
    vectordp(n+1, vector(m+1,0));
    int row=0;
    int col =0;
    int maxi = 0;
    for(int i=1; i

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

    Here is the code for Space Optimization to 1 1D array-
    int lcs(string &str1, string &str2){
    int n = str1.length();
    int m = str2.length();
    int ans = 0;
    vector dp(m+1,0);
    for(int i=1;i=1;j--){
    if(str1[i-1]==str2[j-1]){
    dp[j]= 1+dp[j-1];
    ans=max(ans,dp[j]);
    }
    else dp[j] =0;
    }
    }
    return ans;
    }

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

      Can you explain how this is showing correct results even when we are checking the wrong string indexes like I=1 and j=m in the first iteration

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

    Single 1D Array space optimization:
    int lcs(string &s, string &t){

    int n=s.size(),m=t.size();
    vector cur(m+1,0);
    int maxi=0;
    for(int i=1;i

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

    Understood, Thank you so much.

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

    Memoization Code for this:
    int lcsHelper(string &str1, string &str2, int i, int j, int count, vector& dp) {
    if(i == -1 || j == -1) return count;
    if(dp[i][j][count] != -1) return dp[i][j][count];
    int currentCount = count;
    if (str1[i] == str2[j]) {
    currentCount = lcsHelper(str1, str2, i-1, j-1, currentCount+1, dp);
    }
    currentCount = max({currentCount, lcsHelper(str1, str2, i-1, j, 0, dp), lcsHelper(str1, str2, i, j-1, 0, dp)});
    return dp[i][j][count] = currentCount;
    }
    int lcs(string &str1, string &str2){
    int n = str1.length();
    int m = str2.length();
    vector dp(n, vector(m, vector(max(n, m), -1)));

    return lcsHelper(str1, str2, n-1, m-1, 0, dp);
    }
    We need 3-D vector as striver said :)
    Recursive Code:
    int lcsHelper(string &str1, string &str2, int i, int j, int count) {
    if(i == -1 || j == -1) return count;
    if (str1[i] == str2[j]) {
    count = lcsHelper(str1, str2, i-1, j-1, count+1);
    }
    count = max({count, lcsHelper(str1, str2, i-1, j, 0), lcsHelper(str1, str2, i, j-1, 0)});
    return count;
    }
    int lcs(string &str1, string &str2){
    return lcsHelper(str1, str2, str1.length()-1, str2.length()-1, 0);
    }

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

    If someone can clear my doubt.
    Can someone tell me what does dp[ i ][ j ] means?
    ---
    dp[ 1 ][ 2 ] is 0
    What does dp[ 1 ][ 2 ] means here? What the longest common substring where i = 1 and j = 2; ie str1 = "a" and str2 = "ab"
    I am certain that's not the meaning here since dp[ 1 ][ 2 ] is 0 .
    ---

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

      Dp[1][2] means a from str1 and b from str2. So a and b is not substring so O

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

    The energy man 🙌🔥

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

    understood bhayiya
    as always thank u for all

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

    Memoization solution is not giving correct answer even though i have made the required chages in it.

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

    Can someone please help me in printing the substring.For some reason I am getting the wrong answer while printing the string. Thank you.

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

    amazing teacher.

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

    Understood. Thankyou Sir

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

    Can also be done in O(1) space if we just traverse along the diagonals and keep max consecutive match count

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

      Nah nah, you need the previous values as well.. as in case its not matching. You need to know max!

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

      @@takeUforward
      int ans=0;
      // diagonals starting from first row
      for(int i=0;i

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

    how will we solve this using recursion, memoization?

  • @manjunathg.s5967
    @manjunathg.s5967 2 роки тому +1

    Understood!!

  • @tusharsahu907
    @tusharsahu907 2 роки тому

    understood …excellent series

  • @codingwithanonymous890
    @codingwithanonymous890 2 роки тому +4

    has anyone done by memoization (top down)?

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

      u cannot u need to carry an extra variable!

    • @ShivamMishra-kn8zf
      @ShivamMishra-kn8zf 2 роки тому +1

      @@takeUforward it will be complex but we can do it by third variable right?

    • @surajjoshi3433
      @surajjoshi3433 2 роки тому +4

      Suppose the interviewer asked me this particular question
      , then firstfall i will explain him the subsequence code and what does the table denotes and then this logic. right??
      If i will directly jump into this particular logic then he/she will think i memoize the solution!

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

    why aren't we doing this with the two pointer approach?? we can have total of four pointers... two pointers for the first string and another two pointers for the second string...
    I tried using this approach and 41 test cases passed out of 50 on code ninjas(code 360)... now I don't know which edge case I am missing...

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

    Hey Striver, i m getting wrong ans in java code in space optimization, same happened with lcs space optimization

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

    US striver

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

    I think this can not be solved by memoization ie: top-down won't work here ??
    please reply

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

      I have searched the whole comment section, i couldn't find any memoized code which has passed all test cases
      ig you are right

  • @zhunzargulhane6741
    @zhunzargulhane6741 7 місяців тому

    In space optimization why do we take the length of prev and curr as length of str2.length()+1 why not str1.length()+1.

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

    understood striver

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

    Understood Bhaiya!!
    Edit after 4 months - "UNDERSTOOD BHAIYA!!"

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

    Hey ,i have a doubt according to this code logic, dp[2][2] will get 2 rightt?how zero??? since str1[1]==str2[1] and there is condition to check str1[i]==str2[j]

  • @Coder-zz1tn
    @Coder-zz1tn 4 місяці тому

    "UNDERSTOOD"

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

    Understood sir!

  • @dipaligangawane980
    @dipaligangawane980 2 роки тому

    Very good explanation. Thank you so much.

  • @SumanSingh-gq5vn
    @SumanSingh-gq5vn 2 місяці тому +1

    ye wala clear nhi hua striver bro! ...isme dikkat aai approach m mujhe ...koi samjha sake to please samjhao mujhe

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

    Consistency 🔥

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

    Amazing observation!

  • @explainedmathmaticsranjeet1404

    can we further optimize in 1 d araay?

  • @joshua_dlima
    @joshua_dlima 2 роки тому

    lovely explanation, thanks!

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

    Understood, sir. Thank you very much.

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

    understood sir

  • @raj_kundalia
    @raj_kundalia 2 роки тому

    Thanks for the video!

  • @ll-ex5mh
    @ll-ex5mh 10 місяців тому +1

    Memoization solution with 2d dp C++=>
    class Solution {
    public:
    int memo(int i,int j,vector&dp,vector& nums1, vector& nums2,int &maxlen)
    {
    if(i

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

    Understood, thanks!

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

    Understood 🙂🙂💚🙏

  • @prashantkumar-hx1dv
    @prashantkumar-hx1dv 2 роки тому +1

    cool man

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

    UNDERSTOOD💯💯💯

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

    Understood Thanks 😀

  • @m-bk4um
    @m-bk4um 9 місяців тому

    understand

  • @subasishkar9469
    @subasishkar9469 2 роки тому

    Hi @striver I am not getting the mismatch condition why we are using 0 in this case and have been stuck at it for quite some days now please can you explain , really stuck at this condition

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

    Give the recursive solution to this..

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

      class Solution{
      public:
      int f(int i, int j, string &s1, string &s2, int &ans){

      if( i

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

    thanks a lot sir for the playlist

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

    How to print the longest common substring ?

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

    this is the simplest code
    int longestCommonSubstr (string S1, string S2, int n, int m)
    {
    vector dp(n+1, vector(m+1, 0));
    int maxi=0;
    for(int i=1; i

  • @SohailKhan-cx9gb
    @SohailKhan-cx9gb 11 місяців тому

    Understood bro but the memoization and recursion is quite tough in recursion there is 3d have made😅

  • @Morimove
    @Morimove 7 місяців тому

    bhaiya recursive solution nahi hai kya iska?

  • @InbasekaranP
    @InbasekaranP 2 роки тому +4

    Hey striver, this method of finding the longest common substring fails when there exists a reversed copy of a non-palindromic substring in some other part of S.
    S = “abacdfgdcaba”, S’ = “abacdgfdcaba”.
    The longest common substring between S and S’ is “abacd”. This is not a valid palindrome. As there is a reverse copy of "abcd" ie "dcaba" which is non-palindromic substring in some other part of S, the longest common substring method fails.
    To fix this we just need to check if the substring’s indices are the same as the reversed substring’s original indices. If it is, then we attempt to update the longest palindrome found so far; if not, we skip this and find the next candidate.
    Here is the modified code for the above question:
    ```cpp
    class Solution {
    public:
    string longestPalindrome(string a) {
    int n = a.length();
    string b = {a.rbegin(),a.rend()};
    pair ans = {INT_MIN,{-1,-1}};
    vector dp(n+1,vector(n+1,0));
    for(int i = 1;i

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

      Thanks bro. It helped

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

      For striver code as well we are getting lcs as 5 bro

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

    done with it ! moving to next