algoadvance

Leetcode 2027. Minimum Moves to Convert String

Problem Statement

You are given a string s consisting of lowercase English letters. You are allowed to convert any segment of 3 consecutive characters ‘x’ to ‘O’. You need to return the minimum number of moves required to convert all the ‘x’ characters in the string to ‘O’.

Clarifying Questions

  1. Q: Can segments overlap when converting ‘x’ to ‘O’? A: No, segments can’t overlap. Each segment of 3 consecutive ‘x’s should be independent and non-overlapping.

  2. Q: Do we need to handle any uppercase characters or non-alphabetic characters? A: No, the problem guarantees that the string consists of lowercase English letters only.

  3. Q: What is the expected length range of the input string s? A: Assuming typical LeetCode constraints, length of s is from 1 to (10^5).

Strategy

  1. Traverse the string s while maintaining a current index i.
  2. Whenever an ‘x’ is found at the current index i, increase the counter for moves and skip the next 3 characters (i.e., set i to i + 3).
  3. If the current index is not ‘x’, simply move to the next character (i.e., increment i by 1).

Code

public class Solution {
    public int minimumMoves(String s) {
        int moves = 0;
        int i = 0;
        
        while (i < s.length()) {
            if (s.charAt(i) == 'x') {
                moves++;
                i += 3;
            } else {
                i++;
            }
        }
        
        return moves;
    }
    
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.minimumMoves("xxoxxox")); // Output: 3
        System.out.println(sol.minimumMoves("oxxxxo"));  // Output: 2
        System.out.println(sol.minimumMoves("ooo"));     // Output: 0
        System.out.println(sol.minimumMoves("xxxxx"));   // Output: 2
    }
}

Time Complexity

Feel free to test the implementation with different test cases or edge cases to ensure it covers all scenarios.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI