Minimum Additions to Make Valid String - Problem

You're given a string word that contains only letters 'a', 'b', and 'c'. Your mission is to transform this string into a valid string by inserting the minimum number of additional characters.

A string is considered valid if it can be formed by concatenating the pattern "abc" multiple times. For example:

  • "abc" ✅ (1 repetition)
  • "abcabc" ✅ (2 repetitions)
  • "abcabcabc" ✅ (3 repetitions)
  • "ab" ❌ (incomplete pattern)
  • "acb" ❌ (wrong order)

You can insert 'a', 'b', or 'c' at any position and any number of times. Return the minimum number of insertions needed to make the string valid.

Example: If word = "b", you need to insert 'a' before and 'c' after to get "abc", so the answer is 2.

Input & Output

example_1.py — Basic case
$ Input: word = "b"
Output: 2
💡 Note: We need to insert 'a' before 'b' and 'c' after 'b' to form "abc". Total insertions: 2.
example_2.py — Multiple patterns
$ Input: word = "aaa"
Output: 6
💡 Note: Each 'a' starts a new "abc" pattern. We need 'bc' after each 'a': "abc" + "abc" + "abc". Total insertions: 2 + 2 + 2 = 6.
example_3.py — Complete patterns
$ Input: word = "abc"
Output: 0
💡 Note: The string already forms a complete "abc" pattern, so no insertions are needed.

Constraints

  • 0 ≤ word.length ≤ 50
  • word consists only of letters 'a', 'b', and 'c'
  • Goal: Minimum insertions to make string = "abc" repeated

Visualization

Tap to expand
ABC Pattern RecognitionTarget Pattern:abcrepeat...State Transitions:0Need 'a'1Need 'b'2Need 'c'Example: "bac"1. Start state 0, see 'b' → need 'a' first → +1, go to state 22. State 2, see 'a' → need 'c' first → +1, go to state 13. State 1, see 'c' → need 'b' first → +1, go to state 04. End in state 0 → complete! Total: 3 insertions
Understanding the Visualization
1
Start State
Begin expecting the first piece 'a' of a new abc set
2
Process Each Character
For each character, check if it's the expected next piece
3
Handle Mismatches
If character doesn't match expectation, count insertions needed
4
Update Expectations
Move to next expected state based on current character
Key Takeaway
🎯 Key Insight: Use a state machine to track your position in the "abc" pattern. Each character either advances you to the next state or requires insertions to get back on track.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen