#2027
Minimum Moves to Convert String
EasyStringGreedyGreedySliding Window
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 greedy strategy to convert as many 'X's as possible in one move. By processing the string in a single pass, we can minimize the number of moves required.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for moves to 0.
- 2Step 2: Iterate through the string with an index.
- 3Step 3: Whenever an 'X' is encountered, increment the move counter and skip the next two characters (since they will also be converted).
solution.py15 lines
1# Full working Python code
2
3def minimum_moves(s):
4 moves = 0
5 i = 0
6 while i < len(s):
7 if s[i] == 'X':
8 moves += 1
9 i += 3 # Skip the next two characters
10 else:
11 i += 1
12 return moves
13
14# Example usage
15print(minimum_moves('XXOX')) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Converting three consecutive 'X's in one move is optimal, as it maximizes the number of 'X's converted per move.
- 2Skipping characters after a conversion prevents double counting and reduces unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.