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.
1public class MinCharsAppend {
2 public static int minCharsToAppend(String s, String t) {
3 int sLen = s.length();
4
The Java solution defines a function minCharsToAppend
that iterates over the strings using two indices. The index for t
only increments when a matching character is found in s
. At the end of the iteration, it calculates how many characters of t
are not matched and need to be appended.
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.