2645. Minimum Additions to Make Valid String

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.