Leetcode 2486: Append Characters to String to Make Subsequence

grid47
grid47
Exploring patterns and algorithms
Mar 3, 2024 5 min read

You are given two strings, s and t, consisting only of lowercase English letters. Your task is to determine the minimum number of characters that need to be appended to the end of string s so that string t becomes a subsequence of s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Problem
Approach
Steps
Complexity
Input: Two strings s and t consisting only of lowercase English letters.
Example: s = "hello", t = "world"
Constraints:
• 1 <= s.length, t.length <= 10^5
• Both s and t consist only of lowercase English letters.
Output: Return the minimum number of characters that need to be appended to the end of string s so that t becomes a subsequence of s.
Example: Output: 4
Constraints:
• The returned value will be a non-negative integer.
Goal: Find the minimum number of characters to append to make t a subsequence of s.
Steps:
• 1. Initialize a pointer to iterate through string t.
• 2. Iterate through string s, and whenever a character in s matches the current character in t, move the pointer of t forward.
• 3. At the end, if all characters of t are found in s, return the difference between the length of t and the number of matched characters.
• 4. If not all characters of t are found in s, return the difference between the length of t and the number of matched characters.
Goal: The problem deals with strings of length up to 10^5, so the solution needs to be efficient.
Steps:
• 1 <= s.length, t.length <= 10^5
• Strings s and t consist only of lowercase English letters.
Assumptions:
• The solution assumes that both strings s and t contain only lowercase English letters.
Input: s = "hello", t = "world"
Explanation: For s = "hello" and t = "world", we need to append 'w', 'o', 'r', 'l', 'd' to the end of s to make t a subsequence of s.

Input: s = "abcdef", t = "ace"
Explanation: For s = "abcdef" and t = "ace", no characters need to be appended since t is already a subsequence of s.

Input: s = "a", t = "abc"
Explanation: For s = "a" and t = "abc", we need to append 'b', 'c' to the end of s to make t a subsequence of s.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus