Minimum Additions to Make Valid String Problem
Description
LeetCode Problem 2645.
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.
Solution
Approach: Greedy + Two Pointers
Walk through the pattern abc repeatedly with a pointer i (over "abc") while a pointer j moves along word. If word[j] equals s[i], it matches and j advances; otherwise that letter has to be inserted, so we add 1 to the answer. After each step i moves to the next letter of abc, wrapping around after c. Stop when j reaches the end of word.
The last copy of abc may be unfinished. If word ends with b, a c is missing (add 1); if it ends with a, a b and a c are missing (add 2).
Complexity: O(n) time and O(1) extra space, where n is the length of word.
class Solution:
def addMinimum(self, word: str) -> int:
s = 'abc'
ans, n = 0, len(word)
i = j = 0
while j < n:
if word[j] != s[i]:
ans += 1
else:
j += 1
i = (i + 1) % 3
if word[-1] != 'c':
ans += 1 if word[-1] == 'b' else 2
return ans