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
.
1def minCharsToAppend(s, t):
2 s_len, t_len = len(s), len(t)
3 next_pos = [[s_len] * 26 for _ in range(s_len + 1)]
4
5 last = [s_len] * 26
6 for i in range(s_len - 1, -1, -1):
7 last[ord(s[i]) - ord('a')] = i
8 for j in range(26):
9 next_pos[i][j] = last[j]
10
11 pos = 0
12 append_count = 0
13 for c in t:
14 if next_pos[pos][ord(c) - ord('a')] == s_len:
15 append_count += (t_len - t.index(c))
16 break
17 pos = next_pos[pos][ord(c) - ord('a')] + 1
18
19 return append_count
20
21# Testing the function
22s = "coaching"
23t = "coding"
24print(minCharsToAppend(s, t))
Python's solution defines the next_pos
array, precomputing where each character appears next after each index and using this data to decide how many appended characters are necessary for t
to be its subsequence.