{x}
blog image

Minimum Moves to Convert String

You are given a string s consisting of n characters which are either 'X' or 'O'.

A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.

Return the minimum number of moves required so that all the characters of s are converted to 'O'.

 

Example 1:

Input: s = "XXX"
Output: 1
Explanation: XXX -> OOO
We select all the 3 characters and convert them in one move.

Example 2:

Input: s = "XXOX"
Output: 2
Explanation: XXOX -> OOOX -> OOOO
We select the first 3 characters in the first move, and convert them to 'O'.
Then we select the last 3 characters and convert them so that the final string contains all 'O's.

Example 3:

Input: s = "OOOO"
Output: 0
Explanation: There are no 'X's in s to convert.

 

Constraints:

  • 3 <= s.length <= 1000
  • s[i] is either 'X' or 'O'.

Solution Explanation: Minimum Moves to Convert String

This problem asks for the minimum number of moves to convert a string containing 'X' and 'O' characters into a string containing only 'O' characters. A move consists of selecting three consecutive characters and converting them to 'O'.

The optimal approach is a greedy algorithm. We iterate through the string. Whenever we encounter an 'X', we know we need to perform a move. This move affects three consecutive characters, so we can skip the next two characters as they become 'O' after the move.

Algorithm

  1. Initialization:

    • ans: Initialize a counter to 0, representing the number of moves.
    • i: Initialize a pointer to 0, representing the current index in the string.
  2. Iteration:

    • Iterate through the string using the i pointer.
    • If s[i] == 'X':
      • Increment ans (we need a move).
      • Increment i by 3 (skip the next two characters affected by the move).
    • Else (s[i] == 'O'):
      • Increment i by 1 (move to the next character).
  3. Return: Return the value of ans.

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the string. We iterate through the string at most once.
  • Space Complexity: O(1). We use only a constant amount of extra space for variables.

Code Implementation (Python)

class Solution:
    def minimumMoves(self, s: str) -> int:
        ans = i = 0
        while i < len(s):
            if s[i] == "X":
                ans += 1
                i += 3
            else:
                i += 1
        return ans
 

The code in other languages follows the same logic, differing only in syntax. The core algorithm remains the same greedy approach. Each language version maintains the O(n) time and O(1) space complexity.