Leetcode-editorials
Contribute
  • Leetcode question of the day
  • 08-August
    • 26. Maximum Length of Pair Chain
    • 28. Implement stack using queues
    • 29. Minimum Penalty for a Shop
    • 30. Minimum Replacements to Sort the Array
    • 31. Minimum Number of Taps to Open to Water a Garden
  • 09-September
    • 01. Counting Bits
    • 02. Extra Characters in a String
    • 03. Unique Paths
    • 04. Linked List Cycle
    • 05. Copy List with Random Pointer
    • 06. Split Linked List in Parts
    • 07. Reverse Linked List II
    • 08. Pascal's Triangle
    • 09. Combination Sum IV
    • 10. Count All Valid Pickup and Delivery Options
    • 11. Group the People Given the Group Size They Belong To
    • 12. Minimum Deletions to Make Character Frequencies Unique
    • 13. Candy
    • 14. Reconstruct Itinerary
    • 15. Min Cost to Connect All Points
    • 16. Path With Minimum Effort
    • 17. Shortest Path Visiting All Nodes
    • 18. The K Weakest Rows in a Matrix
    • 19. Find the Duplicate Number
    • 20. Minimum Operations to Reduce X to Zero
    • 21-Median of Two Sorted Arrays
    • 22- Is Subsequence
    • 23- Longest String Chain
    • 24- Champagne Tower
    • 25- Find the Difference
    • 26- Remove Duplicate Letters
    • 27- Decoded String at Index
    • 28- Sort Array By Parity
    • 29- Monotonic Array
    • 30- 132 Pattern
  • 10-October
    • 01. Reverse Words in a String III
    • 02. Remove Colored Pieces if Both Neighbors are the Same Color
    • 03. Number of Good Pairs
    • 04. Design HashMap
    • 05. Majority Element II
    • 06. Integer Break
    • 07. Build Array Where You Can Find The Maximum Exactly K Comparisons
  • 11-November
    • 01. Find Mode in Binary Search Tree
    • 02. Count Nodes Equal to Average of Subtree
    • 03. Build an Array With Stack Operations
    • 04. Last Moment Before All Ants Fall Out of a Plank
    • 07. Eliminate Maximum Number of Monsters
  • Leetcode Contests
    • Weekly Contest
      • Weekly-Contest-360
Powered by GitBook
On this page
  • My Approach
  • Time and Auxiliary Space Complexity
  • Code (C++)
  • Contribution and Support

Was this helpful?

Edit on GitHub
  1. 09-September

23- Longest String Chain

Previous22- Is SubsequenceNext24- Champagne Tower

Last updated 1 year ago

Was this helpful?

The problem can be found at the following link:

My Approach

  1. Custom Comparison Function cmp:

    • Define a static bool function cmp that takes two string parameters, a and b.

    • It compares two strings based on their lengths, returning true if the length of a is less than the length of b, and false otherwise.

  2. isSubsequence Function:

    • Define a member function isSubsequence that takes two string parameters, s and t.

    • Initialize an integer variable j to 0. This variable will be used to iterate through the characters of s.

    • Iterate through the characters of string t using a for loop.

    • Inside the loop, check if the current character in t at index i is equal to the current character in s at index j.

    • If they are equal, increment the j variable.

    • After the loop, check if the length of s is equal to j. If it is, return true, indicating that s is a subsequence of t. Otherwise, return false.

  3. longestStrChain Function:

    • Define a member function longestStrChain that takes a reference to a vector of strings, words.

    • Sort the words vector using the custom comparison function cmp. This sorting is done in ascending order of string lengths.

    • Initialize an integer variable n to store the number of words in the input vector words.

    • Create a dynamic programming (DP) vector dp of size n, where each element represents the length of the longest chain ending with the word at that index. Initialize all elements to 1 because each word forms a chain of length 1 by default.

    • Initialize an integer variable maxLen to 1, which will be used to keep track of the maximum chain length found so far.

  4. DP Loop:

    • Iterate through the words vector using a nested for loop. The outer loop iterates from i = 1 to n-1, and the inner loop iterates from j = 0 to i-1.

    • Inside the inner loop, check if words[j] is a subsequence of words[i] and if the length of words[j] plus 1 is equal to the length of words[i]. This checks if words[i] can be part of a longer chain.

    • If the conditions are met, update the dp[i] value to be the maximum of its current value and dp[j] + 1. This means that we consider extending the chain from word j to word i.

    • Update the maxLen variable with the maximum of its current value and dp[i].

  5. Return Result:

    • After the DP loop, return the value stored in maxLen, which represents the length of the longest string chain that can be formed using the input words.

Time and Auxiliary Space Complexity

  • Time Complexity: O(n*n)

  • Auxiliary Space Complexity: O(n)

Code (C++)


class Solution {
public:
    static bool cmp(string a, string b){
        return a.length()<b.length();
    }
    bool isSubsequence(string s, string t) {
        int j=0;
        for(int i=0; i<t.length();i++){
            if(t[i]==s[j]){
                j++;
            }
        }
        if(s.length()==j)return true;
        return false;
    }

    int longestStrChain(vector<string>& words) {
        sort(words.begin(),words.end(),cmp);
        int n=words.size();
        vector<int> dp(n, 1);
        int maxLen = 1;
        
        for(int i=1; i<n; i++){
            for(int j=0; j<i; j++){
                if(isSubsequence(words[j], words[i]) && words[j].length()+1==words[i].length()){
                    dp[i] = max(dp[i], dp[j]+1);
                }
            }
            maxLen = max(maxLen, dp[i]);
        }
        return maxLen;
    }
};

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.

Question Link
discussion section
rishabhv12/Daily-Leetcode-Solution