Minimum Additions to Make Valid String - Problem

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.

Input & Output

Example 1 — Single Character
$ Input: word = "b"
Output: 2
💡 Note: Insert 'a' before 'b' and 'c' after 'b' to get 'abc'. Total insertions: 2
Example 2 — Partial Pattern
$ Input: word = "aaa"
Output: 6
💡 Note: Each 'a' needs 'bc' to complete 'abc'. Three 'a's need 3×2 = 6 insertions total
Example 3 — Already Valid
$ Input: word = "abc"
Output: 0
💡 Note: String is already valid, no insertions needed

Constraints

  • 1 ≤ word.length ≤ 50
  • word consists only of letters 'a', 'b', and 'c'

Visualization

Tap to expand
Minimum Additions to Make Valid StringbInputabc+1given+1Target: abcAnalysis:• 'b' has no preceding 'a'• 'b' has no following 'c'• Need to insert 'a' + 'c'Transformation Process'b' → 'abc' (insert 'a' at start, 'c' at end)Result: 2 insertions minimum
Understanding the Visualization
1
Input
String 'b' needs to be part of valid 'abc' pattern
2
Analysis
Track what each character needs to form complete 'abc'
3
Output
Minimum insertions needed: 2 (add 'a' and 'c')
Key Takeaway
🎯 Key Insight: Track pending characters that need their ABC pattern completed
Asked in
Google 25 Amazon 20 Microsoft 15
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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