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.
1#include <stdio.h>
2#include <string.h>
3
4int minCharsToAppend(char* s, char* t) {
5 int sLen
The C solution declares a function minCharsToAppend
that takes two strings, s
and t
, and calculates the minimum number of characters required to append to s
to make t
a subsequence. We use two indices to traverse the strings, incrementing sIndex
for each iteration and only incrementing tIndex
when characters match. Finally, we calculate the number of unmatched characters in t
and return it.
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
.
public class MinChars
{
public static int MinCharsToAppend(string s, string t)
{
int sLen = s.Length;
int tLen = t.Length;
int[,] next = new int[sLen + 1, 26];
for (int i = 0; i <= sLen; i++)
for (int j = 0; j < 26; j++)
next[i, j] = sLen;
int[] last = new int[26];
for (int i = 0; i < 26; i++) last[i] = sLen;
for (int i = sLen - 1; i >= 0; i--) {
last[s[i] - 'a'] = i;
for (int j = 0; j < 26; j++)
next[i, j] = last[j];
}
int pos = 0, appendCount = 0;
for (int i = 0; i < tLen; i++) {
if (next[pos, t[i] - 'a'] == sLen) {
appendCount += (tLen - i);
break;
}
pos = next[pos, t[i] - 'a'] + 1;
}
return appendCount;
}
public static void Main()
{
string s = "coaching";
string t = "coding";
Console.WriteLine(MinCharsToAppend(s, t));
}
}
The C# solution works by building the next
table, precomputing where each character can next be found, and uses this table to determine the remaining characters in t
that need appending into s
to maintain order.