LeetCode 2645: Minimum Additions to Make Valid String Solution

Master LeetCode problem 2645 (Minimum Additions to Make Valid String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2645. Minimum Additions to Make Valid String

Problem Explanation

Explanation

To solve this problem, we need to determine the minimum number of letters that must be inserted so that the given string becomes a valid string formed by concatenating "abc" several times. We can achieve this by iterating through the input string and counting the occurrences of each letter. Based on the counts, we can determine how many letters need to be inserted to make the string valid.

Here is the algorithm:

  1. Initialize three counters for each letter 'a', 'b', and 'c'.
  2. Iterate through the input string and count the occurrences of each letter.
  3. Determine the number of letters that need to be inserted based on the counts of 'a', 'b', and 'c'.
  4. Return the total count of letters to be inserted.

The time complexity of this algorithm is O(n), where n is the length of the input string. The space complexity is O(1) since we are using a constant amount of extra space.

Solution Code

class Solution {
    public int minAdditions(String word) {
        int countA = 0, countB = 0, countC = 0;
        for (char c : word.toCharArray()) {
            if (c == 'a') {
                countA++;
            } else if (c == 'b') {
                if (countA <= countB) {
                    countA++;
                } else {
                    countB++;
                }
            } else {
                if (countB == 0) {
                    countA++;
                } else {
                    countB--;
                }
            }
        }
        return countA + countB;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2645 (Minimum Additions to Make Valid String)?

This page provides optimized solutions for LeetCode problem 2645 (Minimum Additions to Make Valid String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2645 (Minimum Additions to Make Valid String)?

The time complexity for LeetCode 2645 (Minimum Additions to Make Valid String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2645 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2645 in Java, C++, or Python.

Back to LeetCode Solutions