Minimum Additions to Make Valid String

medium string greedy two pointers

Problem

You are given a string word made only of the letters "a", "b", "c". You may insert any of these letters anywhere, any number of times. A string is valid if it equals one or more copies of "abc" joined together ("abc", "abcabc", …). Return the minimum number of letters you must insert to make word valid.

Inputword = "b"
Output2
Insert "a" before "b" and "c" after it to get "abc", so 2 insertions are needed.

def addMinimum(word):
    abc = "abc"
    res = 0          # letters we must insert
    j = 0            # pointer into the cyclic "abc" pattern
    for ch in word:
        # insert pattern letters until abc[j] lines up with ch
        while abc[j] != ch:
            res += 1
            j = (j + 1) % 3
        # ch matches abc[j]; consume it and advance
        j = (j + 1) % 3
    # if we stopped mid-block, pad the remaining letters of "abc"
    if j != 0:
        res += 3 - j
    return res
function addMinimum(word) {
  const abc = "abc";
  let res = 0;          // letters we must insert
  let j = 0;            // pointer into the cyclic "abc" pattern
  for (const ch of word) {
    // insert pattern letters until abc[j] lines up with ch
    while (abc[j] !== ch) {
      res += 1;
      j = (j + 1) % 3;
    }
    // ch matches abc[j]; consume it and advance
    j = (j + 1) % 3;
  }
  // if we stopped mid-block, pad the remaining letters of "abc"
  if (j !== 0) res += 3 - j;
  return res;
}
int addMinimum(String word) {
    String abc = "abc";
    int res = 0;          // letters we must insert
    int j = 0;            // pointer into the cyclic "abc" pattern
    for (char ch : word.toCharArray()) {
        // insert pattern letters until abc[j] lines up with ch
        while (abc.charAt(j) != ch) {
            res += 1;
            j = (j + 1) % 3;
        }
        // ch matches abc[j]; consume it and advance
        j = (j + 1) % 3;
    }
    // if we stopped mid-block, pad the remaining letters of "abc"
    if (j != 0) res += 3 - j;
    return res;
}
int addMinimum(string word) {
    string abc = "abc";
    int res = 0;          // letters we must insert
    int j = 0;            // pointer into the cyclic "abc" pattern
    for (char ch : word) {
        // insert pattern letters until abc[j] lines up with ch
        while (abc[j] != ch) {
            res += 1;
            j = (j + 1) % 3;
        }
        // ch matches abc[j]; consume it and advance
        j = (j + 1) % 3;
    }
    // if we stopped mid-block, pad the remaining letters of "abc"
    if (j != 0) res += 3 - j;
    return res;
}
Time: O(n) Space: O(1)