2027. Minimum Moves to Convert String LeetCode Solution

In this guide, you will get 2027. Minimum Moves to Convert String LeetCode Solution with the best time and space complexity. The solution to Minimum Moves to Convert String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Minimum Moves to Convert String solution in C++
  4. Minimum Moves to Convert String solution in Java
  5. Minimum Moves to Convert String solution in Python
  6. Additional Resources
2027. Minimum Moves to Convert String LeetCode Solution image

Problem Statement of 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'.

See also  2037. Minimum Number of Moves to Seat Everyone LeetCode Solution

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

2027. Minimum Moves to Convert String LeetCode Solution in C++

class Solution {
 public:
  int minimumMoves(string s) {
    int ans = 0;

    for (int i = 0; i < s.length();)
      if (s[i] == 'O') {
        ++i;
      } else {
        ++ans;
        i += 3;
      }

    return ans;
  }
};
/* code provided by PROGIEZ */

2027. Minimum Moves to Convert String LeetCode Solution in Java

class Solution {
  public int minimumMoves(String s) {
    int ans = 0;

    for (int i = 0; i < s.length();)
      if (s.charAt(i) == 'O') {
        ++i;
      } else {
        ++ans;
        i += 3;
      }

    return ans;
  }
}
// code provided by PROGIEZ

2027. Minimum Moves to Convert String LeetCode Solution in Python

class Solution:
  def minimumMoves(self, s: str) -> int:
    ans = 0

    i = 0
    while i < len(s):
      if s[i] == 'O':
        i += 1
      else:
        ans += 1
        i += 3

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.