Minimum Moves to Convert String — LeetCode 2027 Python Solution

EasyGreedyString
Problem
#2027
Pattern
Greedy
Reading time
2 min

The problem

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'.

Example

Input
s = "XXX"
Output
1
Explanation
XXX -> OOO

Python solution

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

Complexity

MeasureComplexity
TimeO(n), where n represents the length of the string s
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2027. Minimum Moves to Convert String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2027. Minimum Moves to Convert String?
LeetCode 2027. Minimum Moves to Convert String is rated Easy on LeetCode.
What topics does LeetCode 2027. Minimum Moves to Convert String cover?
LeetCode 2027. Minimum Moves to Convert String is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview