DEV Community

Cover image for Minimum Changes To Make Alternating Binary String Ruby
Gurmukh Singh
Gurmukh Singh

Posted on

Minimum Changes To Make Alternating Binary String Ruby

Problem Statement:

You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.

Return the minimum number of operations needed to make s alternating.

Constraints:

  • 1 <= s.length <= 10^4
  • s[i] is either '0' or '1'. Hint: Traverse String and count 0s and 1s in odd places.

Example 1:

Input: s = "0100"
Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: s = "10"
Output: 0
Explanation: s is already alternating.
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: s = "1111"
Output: 2
Explanation: You need two operations to reach "0101" or "1010".
Enter fullscreen mode Exit fullscreen mode

Solution:

class Solution
  def min_op(s)
    count = 0
    (0...s.length).each do |i|
      if i % 2 != 0
        count += 1 if s[i] == '0'
      else
        count += 1 if s[i] == '1'
      end
    end
    [count, s.length - count].min
  end
end
Enter fullscreen mode Exit fullscreen mode

class Solution: This defines a class named Solution.

def min_op(s): This defines a method named min_op that takes a string s as an argument.

count = 0: Initializes a variable count to keep track of the number of operations.

(0...s.length).each do |i|: This is a loop that iterates over each index i in the range from 0 to the length of the string s (excluding the end value).

if i % 2 != 0: Checks if the index i is odd.

count += 1 if s[i] == '0': If the index is odd and the character at that index in the string is '0', increment the count variable.

else: If the index is even.

count += 1 if s[i] == '1': If the index is even and the character at that index in the string is '1', increment the count variable.

end: Ends the conditional block.

end: Ends the loop.

[count, s.length - count].min: Creates an array containing count and the difference between the length of the string s and count, and then finds the minimum value in the array.

The result of the method is the minimum value calculated in step 11, which represents the minimum number of operations needed to make the string have an alternating pattern of '01' or '10'.

In summary, this Ruby code defines a class Solution with a method min_op that takes a string and calculates the minimum number of operations needed to achieve an alternating pattern of '01' or '10' in the string. The operations involve changing characters at odd or even indices to match the desired pattern.

Top comments (0)