Sponsored
Sponsored
This approach uses two pointers to scan both strings, one pointer for each string. The idea is to attempt to match characters of t
with those in s
. A character from t
is successfully matched if it is equal to the current character in s
. We iterate through s
, moving the pointer for each character matched, while the pointer for t
only moves if a match is found. Once we've iterated through s
, we determine how many characters are left unmatched in t
, which is the number of characters needed to be appended to s
.
Time Complexity: O(n + m) where n is the length of s
and m is the length of t
.
Space Complexity: O(1) as no additional space is used.
1using System;
2
3public class MinChars
4{
5 public static int MinCharsToAppend(string s, string t)
6 {
7 int sLen = s.Length;
8 int tLen = t.Length;
9 int sIndex = 0, tIndex = 0;
10
11 while (sIndex < sLen && tIndex < tLen)
12 {
13 if (s[sIndex] == t[tIndex])
14 {
tIndex++;
}
sIndex++;
}
return tLen - tIndex;
}
public static void Main()
{
string s = "coaching";
string t = "coding";
Console.WriteLine(MinCharsToAppend(s, t));
}
}
This C# solution uses a similar logical approach with two iterators advancing through the strings. It calculates how many characters of t
remain unmatched after scanning through s
This approach uses dynamic programming to precompute the next occurrence of each character for every position in the string s
. By doing so, we quickly identify the existence and location of each character from t
in s
. We build a 2D array next
where next[i][j]
represents the smallest index >= i that holds the character j
in s
. This helps in efficiently determining the position of characters and the necessary additions to the end of the string.
Time Complexity: O(n + m + n * ALPHABET_SIZE) due to preprocessing each character for positions.
Space Complexity: O(n * ALPHABET_SIZE) used by the 2D array next
where n is length of s
.
1function minCharsToAppend(s, t) {
2 const sLen = s.length, tLen = t.length;
3 const nextPos = Array.from({ length: sLen + 1 }, () => Array(26).fill(sLen));
4
5 const last = Array(26).fill(sLen);
6 for (let i = sLen - 1; i >= 0; i--) {
7 last[s.charCodeAt(i) - 'a'.charCodeAt(0)] = i;
8 for (let j = 0; j < 26; j++) {
9 nextPos[i][j] = last[j];
10 }
11 }
12
13 let pos = 0, appendCount = 0;
14 for (const char of t) {
15 if (nextPos[pos][char.charCodeAt(0) - 'a'.charCodeAt(0)] === sLen) {
16 appendCount += tLen - t.indexOf(char);
17 break;
18 }
19 pos = nextPos[pos][char.charCodeAt(0) - 'a'.charCodeAt(0)] + 1;
20 }
21
22 return appendCount;
23}
24
25// Testing the function
26let s = "coaching";
27let t = "coding";
28console.log(minCharsToAppend(s, t));
The JavaScript solution establishes a matrix to track the next locations of each character, easing in the decision to determine which characters remain unmatched and need appending for t
to form a subsequence.