Minimum Moves to Convert String - 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'. 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: For string "XXOX", one optimal approach is to apply a move to positions [0,1,2] which converts "XXO" to "OOO", resulting in "OOOX". Then apply another move to positions [1,2,3] to get "OOOO". Total moves: 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "XXOX"
โ€บ Output: 2
๐Ÿ’ก Note: Apply move at position 0: "XXOX" โ†’ "OOOX". Apply move at position 1: "OOOX" โ†’ "OOOO". Total: 2 moves.
example_2.py โ€” Already Converted
$ Input: s = "OOOO"
โ€บ Output: 0
๐Ÿ’ก Note: All characters are already 'O', so no moves are needed.
example_3.py โ€” Edge Case
$ Input: s = "XXX"
โ€บ Output: 1
๐Ÿ’ก Note: One move at position 0 converts the entire string: "XXX" โ†’ "OOO".

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • s[i] is either 'X' or 'O'
  • Each move converts exactly 3 consecutive characters

Visualization

Tap to expand
๐ŸŽจ Wall Painting AnalogyOriginal Wall: XXOXOXXXXXOXOXXXAfter Move 1 (positions 0-2):OOOXOXXXAfter Move 2 (positions 3-5):OOOOOOXX๐Ÿ–Œ๏ธ Brush covers 3 sections๐Ÿ“ Always start from leftmost Xโšก Skip covered sectionsFinal Result: 3 moves needed
Understanding the Visualization
1
Identify Problem
Locate unpainted sections (X) on the wall
2
Apply Greedy Strategy
Always start painting from the leftmost unpainted section
3
Cover 3 Sections
Each brush stroke covers exactly 3 consecutive sections
4
Skip Covered Areas
Jump over the sections already covered by the current stroke
Key Takeaway
๐ŸŽฏ Key Insight: Greedy works because painting from the leftmost X never wastes strokes - it can only help cover future X's efficiently!
Asked in
Microsoft 15 Amazon 12 Google 8 Apple 5
23.5K Views
Medium Frequency
~12 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen