EasyNo. 2027

Minimum Moves to Convert String — LeetCode 2027 Python Solution

Pattern
Greedy
Topics
Greedy, String
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

PythonSolution
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

Time
O(n)where n represents the length of the string s
Space · auxiliary
O(1) to O(n)

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

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

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.

Free to download. Check it runs on your machine, then pick a plan.