Talentd
FleetCode

2645. Minimum Additions to Make Valid String

Medium50.8% acceptance3 companies

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 <= 50
  • word consists of letters "a", "b" and "c" only. 

Asked at 3 companies

Hints open one at a time

Hint 1
Maintain a pointer on word and another pointer on string “abc”.
Hint 2
If the two characters that are being pointed to differ, Increment the answer and the pointer to the string “abc” by one.
6:48
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def addMinimum(self, word: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"b"
Input
"aaa"
Input
"abc"
Your code is saved on this device.Solution