Alternate It!
Source: codechef
Difficulty: 1789

Alternate It!
Given a binary string$S$.
You can perform a series of operations on it any number of times:
Odd-numbered operations$(1^{st}, 3^{rd}, 5^{th}, ...):$You can shuffle any (possibly empty) substring$^{\dagger}$of$S$in any order.
Even-numbered operations$(2^{nd}, 4^{th}, 6^{th}, ...)$: You can choose any (possibly empty) substring of$S$and
flip
every bit of it.
Flipping a character means turning it from$0$to$1$and vice versa.
Find the
minimum number of operations
to be performed to make the string alternating$^{\ddagger}$.$^{\dagger}$A
substring
of a string is a contiguous sequence of characters within the string.$^{\ddagger}$A string is called
alternating
if no two adjacent characters are the same.
Input Format
The first line of input will contain a single integer$T$, denoting the number of test cases.
Each test case consists of one line - the binary string$S$.
Output Format
For each test case, print a single integer on a new line — the minimum number of operations required to make$S$alternating.
Constraints$1 \leq T \leq 10^{5}$$1 \leq |S| \leq 10^5$The sum of length of strings over all test cases won't exceed$10^{5}$.
Sample 1:
Explanation:
Test case 1:
During the first operation, we can select the entire string as the substring and shuffle it to form$010101$, which is already alternating.
Test case 2:
The given string is already alternating, so no operations are needed.
Test case 3:
During the first operation, choose an empty substring (i.e., make no changes).
During the second operation, flip the$1$at index$4$(zero based indexing).$0101\underline{1}1\xrightarrow{\text{Flip Substring from l=4 to r=4 } }  0101\underline{0}1$.
It can be proven that the initial string cannot be made alternating in less than two operations.

Sample Input:
3
110010
0101
010111

Sample Output:
1
0
2

C++ solution:
#include <bits/stdc++.h>
using namespace std;

int main() {
    // your code goes here
    int t;
    string s;
    cin >> t;
    while(t--){
        cin >> s;
        int n = s.length();
        int ones = 0;
        int zeros = 0;
        for(int i=0;i<n;i++){
            if(s[i] == '1')
            ones++;
            else
            zeros++;
        }
        int flag = 1;
        int prev = s[0];
        for(int i=1;i<n;i++){
            if(s[i] == s[i-1]){
                flag = -1;
            }
            prev = s[i];
        }
        if(flag == 1){
            cout << 0 << endl;
        }
        else{
            int diff = abs(ones-zeros);
            if(diff == 1 || diff == 0){
                cout << 1 << endl;
            }
            else if(diff == 2 || diff == 3){
                cout << 2 << endl;
            }
            else{
                cout << 3 << endl;
            }
        }
    }
}

Go solution:
package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "math"
)

func minimumOperations(sequence string) int {
    length := len(sequence)
    allDifferent := true
    for index := 0; index < length-1; index++ {
        if sequence[index] == sequence[index+1] {
            allDifferent = false
            break
        }
    }
    if allDifferent {
        return 0
    }

    zeroCount := strings.Count(sequence, "0")
    oneCount := strings.Count(sequence, "1")
    difference := int(math.Abs(float64(zeroCount - oneCount)))

    if length%2 == 0 {
        if difference == 0 {
            return 1
        } else if difference == 2 {
            return 2
        } else {
            return 3
        }
    } else {
        if difference == 1 {
            return 1
        } else if difference == 3 {
            return 2
        } else {
            return 3
        }
    }
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    var testCases int
    fmt.Fscanf(reader, "%d\n", &testCases)

    for caseIndex := 0; caseIndex < testCases; caseIndex++ {
        sequence, _ := reader.ReadString('\n')
        sequence = strings.TrimSpace(sequence)
        fmt.Println(minimumOperations(sequence))
    }
}

Java solution:
import java.io.*;
import java.util.*;

class Codechef {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }


    public static void main(String[] args) throws IOException {
        FastReader in = new FastReader();
        PrintWriter out = new PrintWriter(System.out);

        int T = in.nextInt();
        while (T-- > 0) {
            String s = in.next();
            int n = s.length();
            boolean flag = true;
            int zeros=0, ones=0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '0') {
                    zeros++;
                } else {
                    ones++;
                }
                if (i < n - 1 && s.charAt(i) == s.charAt(i + 1))
                    flag = false;

            }
            int diff=Math.abs(zeros-ones);
            if (flag) {
                out.println("0");
            }
            else if(diff<=1) {
                out.println("1");
            } else {
                if(diff<=3)
                    out.println("2");
                else
                    out.println("3");
            }
        }

        out.flush();
        out.close();
    }
}

JavaScript solution:
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on("line", (line) => {
    input.push(line.trim());
}).on("close", () => {
    let T = parseInt(input[0]); // Number of test cases
    let results = [];

    for (let i = 1; i <= T; i++) {
        let s = input[i];
        results.push(computeAnswer(s));
    }

    console.log(results.join("\n"));
});

// Function to check if the string is alternating
function isAlternating(s) {
    for (let i = 1; i < s.length; i++) {
        if (s[i] === s[i - 1]) return false;
    }
    return true;
}

// Function to compute the answer based on given conditions
function computeAnswer(s) {
    let n = s.length;
    if (isAlternating(s)) return 0;

    let count0 = 0;
    for (let c of s) {
        if (c === '0') count0++;
    }

    if (n % 2 === 0) {
        let target = n / 2;
        if (count0 === target) return 1;
        else if (Math.abs(count0 - target) === 1) return 2;
        else return 3;
    } else {
        let tA = Math.floor(n / 2);
        let tB = n - tA;
        if (count0 === tA || count0 === tB) return 1;
        else if (Math.abs(count0 - tA) === 1 || Math.abs(count0 - tB) === 1) return 2;
        else return 3;
    }
}

Python solution:
# cook your dish here
def is_alternating(s: str) -> bool:
    for i in range(len(s) - 1):
        if s[i] == s[i+1]:
            return False
    return True

def min_operations(s: str) -> int:
    # If already alternating, no operation is needed.
    if is_alternating(s):
        return 0

    n = len(s)
    count0 = s.count('0')
    count1 = s.count('1')

    # For even length strings
    if n % 2 == 0:
        # Valid alternating string must have n/2 zeros and n/2 ones.
        if count0 == n // 2:
            return 1
        imbalance = abs(count0 - (n // 2))
    else:
        # For odd length, the valid configuration is:
        # if more 0's then valid count0 = (n+1)//2; if more 1's then valid count1 = (n+1)//2.
        expected_major = (n + 1) // 2  # for the majority element
        if max(count0, count1) == expected_major:
            return 1
        imbalance = max(count0, count1) - expected_major

    if imbalance == 1:
        return 2
    else:
        return 3

def solve():
    import sys
    data = sys.stdin.read().strip().split()
    if not data:
        return
    t = int(data[0])
    results = []
    for i in range(1, t+1):
        s = data[i].strip()
        results.append(str(min_operations(s)))
    sys.stdout.write("\n".join(results))

if __name__ == '__main__':
    solve()

Ruby solution:
def solve_alternate_it
  t = gets.to_i
  t.times do
    s = gets.to_s.chomp
    next if s.empty?  # though constraints say |S| >= 1
    
    # Check if already alternating
    is_alternating = true
    (1...s.length).each do |i|
      if s[i] == s[i-1]
        is_alternating = false
        break
      end
    end

    if is_alternating
      puts 0
      next
    end

    # Count digits
    count0 = s.count('0')
    count1 = s.count('1')
    imbalance = (count0 - count1).abs

    # Determine minimum operations
    case imbalance
    when 0..1 then puts 1
    when 2..3 then puts 2
    else puts 3
    end
  end
end

solve_alternate_it