Minimum Additions to Make Valid String — LeetCode 2645 Python Solution

MediumStackGreedyStringDynamic Programming
Problem
#2645
Pattern
Stack
Reading time
3 min

The 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.

Example

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".

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string word
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2645. Minimum Additions to Make Valid String is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2645. Minimum Additions to Make Valid String?
LeetCode 2645. Minimum Additions to Make Valid String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2645. Minimum Additions to Make Valid String?
The Python solution on this page runs in O(n), where n is the length of the string word.
What is the space complexity of LeetCode 2645. Minimum Additions to Make Valid String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2645. Minimum Additions to Make Valid String cover?
LeetCode 2645. Minimum Additions to Make Valid String is tagged Stack, Greedy, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview