2645. Minimum Additions to Make Valid String
Description
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid.
A string is called valid if it can be formed by concatenating the string "abc" several times.
Example 1:
Input: word = "b" Output: 2 Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "b" to obtain the valid string "abc".
Example 2:
Input: word = "aaa" Output: 6 Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc".
Example 3:
Input: word = "abc" Output: 0 Explanation: word is already valid. No modifications are needed.
Constraints:
1 <= word.length <= 50wordconsists of letters "a", "b" and "c" only.
Solutions
Solution 1: Greedy + Two Pointers
Thinking
The target is concatenations of abc, and we may only insert. A DP over split points would pass for \(n \le 50\), but the match advances greedily.
Walk the repeating pattern abc: a mismatch counts as an insertion, a match consumes one character of \(word\). After the scan, pad with the missing suffix if the last letter is not c.
We define the string \(s\) as "abc", and use pointers \(i\) and \(j\) to point to \(s\) and \(word\) respectively.
If \(word[j] \neq s[i]\), we need to insert \(s[i]\), and we add \(1\) to the answer; otherwise, it means that \(word[j]\) can match with \(s[i]\), and we move \(j\) one step to the right.
Then, we move \(i\) one step to the right, i.e., \(i = (i + 1) \bmod 3\). We continue the above operations until \(j\) reaches the end of the string \(word\).
Finally, we check whether the last character of \(word\) is 'b' or 'a'. If it is, we need to insert 'c' or 'bc', and we add \(1\) or \(2\) to the answer and return it.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(word\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |