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

Input & Output

Example 1 — Basic Case
$ Input: s = "XXX"
Output: 1
💡 Note: We can convert all three X's to O's with a single move: one move converts "XXX" to "OOO"
Example 2 — Mixed Characters
$ Input: s = "XXOX"
Output: 2
💡 Note: First move at position 0 converts "XXOX" to "OOOX", second move at position 3 converts it to "OOOO"
Example 3 — Already Converted
$ Input: s = "OOOO"
Output: 0
💡 Note: All characters are already 'O', so no moves are needed

Constraints

  • 1 ≤ s.length ≤ 1000
  • s[i] is either 'X' or 'O'

Visualization

Tap to expand
Minimum Moves to Convert String INPUT String s = "XXX" X index 0 X index 1 X index 2 Input Parameters s = "XXX" n = 3 characters Goal: Convert all 'X' to 'O' using minimum moves (each move converts 3 chars) ALGORITHM STEPS 1 Initialize moves = 0, i = 0 2 Scan Left to Right Check s[i] at each pos 3 If s[i] == 'X' moves++, skip 3 (i+=3) 4 Else (s[i] == 'O') Just advance (i++) Trace for "XXX" i=0: s[0]='X' moves=1 O O O converted! i=3: i >= n, DONE return 1 FINAL RESULT Before (Input) X X X After (1 Move) O O O 1 move covers all 3 Output: 1 Minimum Moves = 1 Key Insight: Greedy Left-to-Right Scan When we find an 'X', we convert 3 consecutive characters starting from that position. This is optimal because any 'X' must be covered, and converting early covers the most ground. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Minimum Moves to Convert String | Greedy Approach
Asked in
Microsoft 25 Amazon 20
28.5K Views
Medium Frequency
~8 min Avg. Time
892 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