#2645
Minimum Additions to Make Valid String
MediumStringDynamic ProgrammingStackGreedyTwo PointersGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass through the string with two pointers, one for the input string and one for the pattern 'abc'. This allows us to efficiently count how many characters need to be added without redundant checks.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one for the input string and one for the pattern 'abc'.
- 2Step 2: Loop through the input string, comparing each character with the current character in the pattern.
- 3Step 3: If the characters match, move both pointers forward.
- 4Step 4: If they don't match, increment the additions count and only move the pattern pointer forward.
- 5Step 5: After processing the input string, add any remaining characters needed from the pattern to the additions count.
solution.py12 lines
1def minAdditions(word):
2 pattern = 'abc'
3 i, j, additions = 0, 0, 0
4 while i < len(word):
5 if word[i] == pattern[j]:
6 j += 1
7 else:
8 additions += 1
9 i += 1
10 j %= 3
11 additions += (3 - j) % 3
12 return additionsℹ
Complexity note: The complexity is O(n) because we only make a single pass through the input string, making it much more efficient than the brute-force approach.
- 1Understanding how to compare characters in a cyclic pattern is crucial.
- 2Recognizing when to increment the additions count helps streamline the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.