DP 45. Longest String Chain | Longest Increasing Subsequence | LIS

Поділитися
Вставка
  • Опубліковано 5 лют 2025
  • Lecture Notes/C++/Java Codes: takeuforward.o...
    Problem Link: bit.ly/3KHsl9J
    Please watch the video at 1.25x for a better experience.
    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 Longest String Chain, prior to this please solve dp 41 and dp 42.
    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...

КОМЕНТАРІ • 271

  • @manasgupta4393
    @manasgupta4393 2 роки тому +21

    in checkPossible method, add condition if(j

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

      yep
      bool isPossible(string &s1, string &s2){
      if(s1.size()!=s2.size()+1) return false;
      int i=0,j=0;
      while(i

    • @AbhishekKumar-yv6ih
      @AbhishekKumar-yv6ih 11 місяців тому

      It didn't fail for me, simply goes to else condition, when j breaches s2.

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

    UNDERSTOOD.........Thank You So Much for this_wonderful video.........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @ToonTorque
    @ToonTorque 2 роки тому +14

    In case anyone is struggling with the java code here it is
    here i have did this one on leetcode and its working as the maxi is returning the length of the array so i started it from 0 and added 1 in the end for the correct length
    static int lSC(String[] arr){
    Arrays.sort(arr, Comparator.comparingInt(String::length));
    int n = arr.length;
    int[] dp = new int[n];
    int maxi = 0;
    for (int i = 0; i < n; i++) {
    for (int j = 0; j < i; j++) {
    if (checkPossible(arr[i], arr[j]) && 1 + dp[j] > dp[i]){
    dp[i] = 1+ dp[j];
    }
    }
    if (dp[i] > maxi){
    maxi = dp[i];
    }
    }
    return maxi + 1;
    }
    private static boolean checkPossible(String s, String s1) {
    if (s.length() != s1.length()+1){
    return false;
    }
    int first = 0;
    int second = 0;
    while (first < s.length()){
    if (second < s1.length() && s.charAt(first) == s1.charAt(second)){
    first++;
    second++;
    }
    else {
    first++;
    }
    }
    if (first == s.length() && second == s1.length()){
    return true;
    }
    else return false;
    }

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

      but why you have not filled dp array with 1 and do the standarad lis ? why it giving error?

  • @JayPatel-sn7it
    @JayPatel-sn7it Рік тому +2

    What an amazing thought process. I haven't seen anywhere yet.

  • @dennyage4791
    @dennyage4791 2 роки тому +21

    Checkboolean() function will throw out of index error when S1: abcd , S2: abc

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

      we can add if(second==s2.size()) return true; ,in the while loop

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

      if (i == n or i == n-1) and j == m:
      return True
      return False
      use above syntax

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

      s1 will always be smaller than s2, as array is sorted

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

    Bro make some videos on game theory, it's highly needed!! Couldn't find any better content on yt.

    • @TechWithKomal
      @TechWithKomal 2 роки тому +9

      I have made few game theory videos, you could check them also, I hope that would help for time being , but would love to see videos by striver :)

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

    As always "understood" ❤️

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

    Understood! Thank you veeeeeery much as always!!

  • @satyamgupta1446
    @satyamgupta1446 2 роки тому +36

    you can also check the both Strings by using lcs and if len(lcs) == smaller string then it is true else false.
    class Solution {
    public boolean isValid(String s,String t)
    {
    int n=s.length();
    int m= t.length();
    if(n-m!=1) return false;
    int[][] dp=new int[n+1][m+1];
    for(int i=1;i

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

      this will give tle

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

      This solution will have more TC and SC

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

      @@ayushgupta80 This will not get TLE for this particular problem as maximum size of the words[I] is 16. it will have larger TC = O(16*16*N*N) and also SC of an additional O(N*M)

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

      @@mohaimenchowdhury its giving tle on LC though.

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

      Great observation bro

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

    Learnt how to check for subsequence using two pointers.

  • @studynewthings1727
    @studynewthings1727 9 місяців тому +1

    Understood.

  • @ntgrn-pr5yx
    @ntgrn-pr5yx 3 місяці тому

    understood , thank you striver

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

    Now , i feel so much confidance . i applied same exact code and i came just to see your stretegy. 😃

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

      that's the best feeling in the world

  • @amitkulkarni9682
    @amitkulkarni9682 9 місяців тому +1

    solved this without watching because of Striver !!!

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

    Thank you
    Understood!

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

    Understood ❤

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

    We love you striver!!!

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

    in c++ your comp function should be static since sort() is static .(if code is in class)

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

    #understood....thanku striver

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

    Understood:)

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

    Thank you , understood.

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

    you are amazing sir

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

    i am getting tle with recursive dp on last test case .. can it be done with recursive dp?

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

    keeping the idea simple and building up the solution is a rare art only our Savior Striver possesses . Thankyou for amazing solution Striver

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

    Understood, sir. Thank you very much.

  • @Himani-t3g
    @Himani-t3g 3 місяці тому

    understood!

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

    another complex way of solving it using recursion(c++)
    #include
    bool compare(string &s1,string &s2)
    {
    return s1.size() < s2.size();
    }
    int lcs(string &s,string &t,int idx1,int idx2){
    if(idx1 < 0 || idx2 < 0){
    return 0;
    }
    if(s[idx1] == t[idx2]){
    int pick = 1+lcs(s,t,idx1-1,idx2-1);
    return pick;
    }
    return max(lcs(s,t,idx1-1,idx2),lcs(s,t,idx1,idx2-1));
    }
    int solve(vector&arr,int idx,int n,int prev_idx){
    if(idx == n){
    return 0;
    }
    if(prev_idx == -1 || (arr[idx].length()-lcs(arr[idx],arr[prev_idx],arr[idx].length()-1,arr[prev_idx].length()-1) == 1 && arr[idx].length() == 1 + arr[prev_idx].length())){
    int pick = 1 + solve(arr,idx+1,n,idx);
    int dontpick = solve(arr,idx+1,n,prev_idx);
    return max(pick,dontpick);
    }
    return solve(arr,idx+1,n,prev_idx);
    }
    int longestStrChain(vector &arr)
    {
    sort(arr.begin(),arr.end(),compare);
    int n = arr.size();
    return solve(arr,0,n,-1);
    }

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

    cant find in which video you explained the LIS code you typed in the begining of this video. Please help.

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

    Understood Sir, Thank you very much

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

    Striver, I have a question: for Time Complexity when do you know when to multiply the length by N^2 and when to just add it. In the last problem you added it, but here you multiplied it. May anyone who can help tell me the intuition here? and thx.
    Of course THANK YOU STRIVERRR. You are the best bhaiya!!

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

      Anything inside nested loops (Eg. "for loop till n" and "for loop of prev" and the "checkPossible" function) are multiplied and if some block of code is outside nested loops, it's added to the complexity.
      Hence here, (first loop runs till N) * (Second loop of previous runs till N) * (checkPossible function runs till max length of the string) = (N^2) * len
      If our checkPossible function was outside these loops then it would have been added and not multiplied.
      Therefore, Multiplication is done from the outermost loop of any nested block till the interiormost loop.

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

      ​@@aniket7512 Ohh!! What about when we have recursion or some other operations? How do we know the time complexity? Or is it just based on the loops?
      And thanks a ton for answeringg!! Much appreciated!

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

      @@tasneemayham974 Recursion case complexity is calculated by visualising the recursion tree with the depth and the branches it goes. Try some examples on ur own with the previous videos of striver's.
      If not let me know if any doubt u have.

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

      @@aniket7512 Ahh yes!! Actually I watched his whole series and that's the only way I calculate the TC. I just thought there was another rule for that! So, thanks for clearing that up!! You were really helpful!! BIG THANKS BRO!

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

    is it possible to solve this by tabulation approach, or memorization approach

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

    In checkpossible function, in not match case, shouldnt it be second++ as, s2 being the larger string

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

    Great Explanation

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

    understood ,able to solve by my own

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

    Understood, thanks!

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

    What does he mean when he says "shuttle changes"?

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

    How does the comparison
    s1[first] == s2[second] work in case we overshoot second to be greater than s2.size ?
    Wouldn’t s2[second] in that case would give a segmentation fault ?

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

      need to one more condition in if( second < s2.size() && s1[first] == s2[second] )

  • @VikashYadav-px8ei
    @VikashYadav-px8ei Рік тому +1

    Understood 🎉

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

    understood

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

    thanks

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

    understood!!

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

    Understood!!!Thank you

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

    Understood!

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

    what is the time complexity of recursion code of this question? recursion code accept on gfg.

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

    Understood.

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

    checkPossible method should return false when s1 = "aa" and s2 = "aa". But currently it returns true

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

    in c++ if getting error in comparator function make it :- static bool comp

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

    Understood. Amazing !

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

    Another way of doing - using Recursion (top-down)
    No need to sort as we try out all possibilities.
    Take any word from the list ["xbc","pcxbcf","xb","cxbc","pcxbc"]
    Ex - pcxbcf
    try to generate all substrings of it by deleting one character at a time(as the predecessor is one length less than the current word) and check if it is in the given list.
    cxbcf
    pxbcf
    pcbcf
    pcxcf
    pcxbf
    pcxbc
    If the generated substrings are in the list, you can continue with the process else, go with the next substring. Repeat this process for all the words in the given list and return the max length.
    words=["xbc","pcxbcf","xb","cxbc","pcxbc"]
    seen=set(words)
    def f(s):
    if len(s)==1:
    return 1 if s in seen else 0
    ans=0
    for i in range(len(s)):
    sub=s[0:i]+s[i+1:]
    if sub in seen: ans=max(ans,f(sub))
    return 1+ans
    ans=0
    for word in words:
    ans=max(ans,f(word))
    return ans
    As you can see there are overlapping sub-problems in it --> For the substrings cxbcf and pxbcf (and others) we are calculating the results for xbcf >1 time, So you can easily memoize the solution.

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

      what will be the time complexity of this ?

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

      sorting actually reduce the number of comparisons of 2 strings pair as we wont be iterating for all string only those who are less than it, or can be done with the help of map as well, if you done word ladder, similar kind of approach

  • @561skumar4
    @561skumar4 2 роки тому

    "understood" ❤

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

    For C++ add this condition in the compare function in the end:
    else if(j == word2.size())
    return 1;
    and also make the custom comparator function static

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

      Correct if you dont declare the bool functions static it gives TLE on leetcode
      Leetcode has very tight constraints.

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

      Can you explain how adding that else condition takes care of the case where s1=abcd and s2=abc?

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

      // t.c - O(nlogn) + O(n^2m);
      class Solution {

      bool checkPossible(string &s1, string &s2) {

      // ith string has to be one greater than the prev
      if(s1.size() != s2.size() +1) {
      return false;
      }

      int first = 0, second = 0;
      while(first < s1.size() && second < s2.size()) {
      if(s1[first] == s2[second]) {
      first++;
      second++;
      }
      else{
      first++;
      }
      }

      if(first == s1.size() && second == s2.size()) return true;
      else if(second == s2.size()) return true;
      return false;
      }


      static bool comp(string &s1, string &s2) {
      return s1.size() < s2.size();
      }


      public:
      int longestStrChain(vector& arr) {
      int n = arr.size();

      // sort acc. to the length of string
      sort(arr.begin(), arr.end(), comp);

      for(int i=0;i

    • @Shubham-or6cs
      @Shubham-or6cs 2 роки тому +2

      class Solution {
      public:
      static bool comp(string s1, string s2){
      return s1.size()

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

      @@Shubham-or6cs ["xbc","pcxbcf","xb","cxbc","pcxbc"] on this TC ?

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

    Hey it would be a great help if you upload the notes and java code on your website, for these programs.

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

      notes are there if you see in description and java code can be found in comments down below

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

    Understood!!!!!

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

    Python solution:
    def isPredecessor(strI, strPrev):
    if len(strI) != (len(strPrev) + 1): return False
    p1 = p2 = 0
    while p1 < len(strI):
    if p2 < len(strPrev) and strI[p1] == strPrev[p2]:
    p2 += 1
    p1 += 1

    return p1 == len(strI) and p2 == len(strPrev)
    class Solution:
    def longestStrChain(self, words: List[str]) -> int:
    words.sort(key=len)
    ans, n = 1, len(words)
    dp = [1] * n
    for i in range(n):
    for prev in range(i):
    if isPredecessor(words[i], words[prev]):
    dp[i] = max(dp[i], dp[prev] + 1)
    ans = max(ans, dp[i])
    return ans

  • @techie-alien4712
    @techie-alien4712 2 роки тому +1

    hey striver! I can't find the notes for this problem on takeUforward website. is it still not updated? do we have to wait?

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

      Yes end of june is expected date

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

      @@takeUforward we are waiting

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

      @@takeUforward We are still waiting for the notes to be uploaded.

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

    Sir please also make a video on scramble string

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

    Getting Time Limit Exceeded on leetcode, any suggestions for optimization ?

    • @ShubhamKumar-ur1vm
      @ShubhamKumar-ur1vm 2 роки тому +9

      in checkPossible function , pass the two strings as reference like &str1 ,&str2

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

      if(words[i].size() == words[j].size() +1 ) .....use this condition before compare condition

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

      @@ShubhamKumar-ur1vm now its working lol but why???

  • @AmanPatel-ub7sw
    @AmanPatel-ub7sw 2 роки тому

    understood ❤

  • @shubhamsharma-mj7ou
    @shubhamsharma-mj7ou 2 роки тому

    Can I print subsequence only using iteration not using power set in iteration of possible can you make a video on that

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

    use static bool cmp on leetcode else it wont work and also declare string with const string in the cmp function

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

      sort(arr.begin(),arr.end(),[](string a,string b){
      return a.size()

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

      @@getthejobdone5419 It looks more complex than just adding static

  • @adityaraj-zm7zk
    @adityaraj-zm7zk 10 місяців тому

    why we write s1.size() != s2.size() +1)

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

    I am getting a tle for the same code on leetcode, can anyone suggest how to resolve it .

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

      Try sorting the given string based on len and break the second loop if the diff of lengths is >1
      for index in range(len(words) :
      for prevIndex in range(index-1,-1,-1) :
      lenCondition>1: break

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

    Understood 😇

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

    Understood!!!!

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

    Undertoor, thanks

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

    understood sir🙏❤

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

    why take and notTake approach is not working in this ?

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

    Understood

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

    Comparison function if s1=cbd and s2=bc it will not work ?? Can anyone explain

    • @AdityaKumar-y7g7k
      @AdityaKumar-y7g7k 6 місяців тому

      we can't change the order of b and c. check on leetcode its clearly mentioned order have to be same. only 1 character can be inserted anywhere in the string for new member of chain

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

    Understood
    But can anyone let me know how to figure out that this question has to be solved using LIS pattern

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

    Has anyone found striver's comparator 15:11 video?

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

    understood'

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

    Understood !!!!!!!!!!!!!!!!!

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

    Can we do this using the binary search logic as well??
    If yes , can anyone put the code

  • @m-bk4um
    @m-bk4um Рік тому

    understand

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

    Understood💪💪💪

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

    understood!

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

    Understood ❣️

  • @RahulSharma-ht2xz
    @RahulSharma-ht2xz Рік тому

    tooooooooooooo goooooooooooood

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

    understood❤❤

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

    understood dude:)

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

    Understood!

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

    DP Revision:
    Had to watch whole of the video to get the logic ;-;
    Nov'20, 2023 04:42 pm

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

    It can be done in N*L right ?

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

    understood!!!!

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

    i thought of exact same approach but it gives tle on leetcode:(

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

    Understood Sir!

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

    understood!!

  • @YashveerGahlot-t6b
    @YashveerGahlot-t6b 5 місяців тому

    "understood"

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

    good raj vikram aditya

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

    Understood!!!

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

    genius

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

    understood

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

    Understood Sir :)

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

    Java Code for this?

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

      Check out my solution,
      leetcode.com/problems/longest-string-chain/discuss/2223228/Java-Simple-solution

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

    Understood Sir

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

    Anyone getting static error use this:
    static bool sor(string &a, string &b) {
    return a.size() < b.size();
    }

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

    public static boolean compare(String s1, String s2){
    int first = 0;
    int second = 0;
    int diff = 0;
    while (first < s1.length()){
    if(second < s2.length() && s1.charAt(first) == s2.charAt(second)){
    first++;
    second++;
    }else{
    diff++;
    first++;
    }
    }
    if(first == s1.length() && second == s2.length() && diff == 1){
    return true;
    }else {
    return false;
    }
    }
    // //Check Predecessor by checking LCS and then use LIS logic.
    // public static int lcs(String a, String b, int i, int j, int[][] dp){
    // if(i

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

    #include
    using namespace std;
    bool comp(string &s1, string &s2)
    {
    return s1.size() < s2.size();
    }
    bool checkstr(string &s1, string &s2)
    {
    if(s1.size()!=s2.size()+1) return false;
    int first=0, second=0;
    while(first < s1.size() && second < s2.size())
    {
    if(second

    • @Shubham-or6cs
      @Shubham-or6cs 2 роки тому

      Same problem

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

      the while loop should run s1.size() times
      so while(first < s1.size())

    • @jayant-baid
      @jayant-baid Рік тому +4

      Make comp func static

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

      Make comp static and run the while loop for(first

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

    Here is my memoization code. which gave me TLE.
    struct compare {
    inline bool operator()(const std::string& first,
    const std::string& second) const
    {
    return first.size() < second.size();
    }
    };
    bool check(string s , string t){
    int n = s.length() , m = t.length() , count = 0 , i = 0 , j = 0;
    if(m != (n + 1)) return false;
    while(i < n){
    if(s[i] == t[j]){
    i++ , j++;
    }
    else{
    count++;
    j++;
    }
    if(count >= 2) return false;
    }
    return true;
    }
    int solve(int i , int prev , vector < string > &v , vector < vector < int > > &dp){
    int n = v.size();
    if(i == n) return 0;
    if(dp[i][prev + 1] != -1) return dp[i][prev + 1];
    int len = solve(i + 1, prev , v, dp); // notTake
    if(prev == -1 || check(v[prev] , v[i])){
    int take = 1 + solve(i + 1 , i , v , dp);
    len = max(len , take);
    }

    return dp[i][prev + 1] = len;
    }
    int longestStrChain(vector& words) {
    int n = words.size();
    compare c;
    sort(words.begin() , words.end() , c);
    vector < vector < int > > dp(n , vector < int > (n + 1 , -1));
    return solve(0 , -1 , words , dp);
    }
    ---------------------------------------------------------Tabulation---------------------------------------------
    int longestStrChain(vector& arr) {
    int n = arr.size() , maxLen = 1;
    compare c;
    sort(arr.begin() , arr.end() , c);
    vector < int > dp(n , 1);
    for(int i = 0; i < n; i++){
    for(int j = 0; j < i; j++){
    if(check(arr[j] , arr[i])){
    dp[i] = max(dp[i] , dp[j] + 1);
    maxLen = max(maxLen , dp[i]);
    }
    }
    }
    return maxLen;
    }