Problem Description
Given a string s consisting of characters 'X' and 'O', the task is to convert all characters to 'O' using the minimum number of moves. In one move, you can select any three consecutive characters and convert them all to 'O'. The goal is to determine the minimum number of moves required to achieve a string of all 'O's.
Key Insights
- A greedy approach works because converting three consecutive characters maximizes the number of 'X's turned to 'O's in one move.
- When an 'X' is encountered, applying a move starting at that index will set the next two characters to 'O', so you can skip the next two characters.
- If encountered spans of 'O's, you simply move to the next character.
- Moving the pointer by three after converting saves redundant operations.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string since we iterate through the string once. Space Complexity: O(1), as only a few variables are used.
Solution
The solution employs a greedy algorithm. Traverse the string from left to right using an index pointer. Each time an 'X' is encountered, apply a move (simulate by incrementing the counter) and skip the next two characters because they are guaranteed to be changed to 'O' by this move. This ensures that each move covers as many 'X's as possible. The pointer skips ahead by three positions after each move. If the character is 'O', simply move to the next character.