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.
1def minCharsToAppend(s, t):
2 s_len, t_len = len(s), len(t)
3 s_index, t_index = 0, 0
4
The Python solution defines the function minCharsToAppend
where two indices are used to iterate over the strings. For every matched character, the index of t
moves forward. The number of unmatched characters in t
is returned as the count of characters to append.
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
.
1import java.util.Arrays;
2
3public class MinCharsAppend {
4 public static int minCharsToAppend(String s, String t) {
5 int sLen = s.length(), tLen = t.length();
6 int[][] next = new int[sLen + 1][26];
7
8 for (int[] row : next) {
9 Arrays.fill(row, sLen);
10 }
11
12 int[] last = new int[26];
13 Arrays.fill(last, sLen);
14
15 for (int i = sLen - 1; i >= 0; i--) {
16 last[s.charAt(i) - 'a'] = i;
17 System.arraycopy(last, 0, next[i], 0, 26);
18 }
19
20 int pos = 0, appendCount = 0;
21 for (int i = 0; i < tLen; i++) {
22 if (next[pos][t.charAt(i) - 'a'] == sLen) {
23 appendCount += (tLen - i);
24 break;
25 }
26 pos = next[pos][t.charAt(i) - 'a'] + 1;
27 }
28
29 return appendCount;
30 }
31
32 public static void main(String[] args) {
33 String s = "coaching";
34 String t = "coding";
35 System.out.println(minCharsToAppend(s, t));
36 }
37}
The Java solution involves creating a next
array storing indices of upcoming occurrences of each character. It then strategically plans the minimal additions required by staying aware of precomputed locations.