Find the fewest character flips that make a binary string alternate

Quick Overview

Given a binary string, find the fewest single-character changes that make every pair of adjacent characters different. It is an easy string scanning problem that tests a short counting argument and careful handling of where the string starts.

Find the fewest character flips that make a binary string alternate

Company: Tesla

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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 any `'1'` to `'0'`. The string is called alternating if no two adjacent characters are equal. For example, `"010"` is alternating, while `"0100"` is not. Return the minimum number of operations needed to make `s` alternating. ### Function Signature ```python def min_operations(s: str) -> int: ``` ### Constraints - `1 <= len(s) <= 10^4` - `s[i]` is either `'0'` or `'1'`. ### Examples ```text Input: s = "0100" Output: 1 ``` Changing the last character from `'0'` to `'1'` gives `"0101"`, which is alternating. The string is not alternating to begin with, so at least one operation is needed. ```text Input: s = "10" Output: 0 ``` `"10"` is already alternating, so no operations are needed. ```text Input: s = "1111" Output: 2 ``` Both alternating strings of length 4, `"0101"` and `"1010"`, differ from `"1111"` in two positions.

Overview: Given a binary string, find the fewest single-character changes that make every pair of adjacent characters different. It is an easy string scanning problem that tests a short counting argument and careful handling of where the string starts.

Tesla logo
Tesla
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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 any '1' to '0'.

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

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

Function Signature

def min_operations(s: str) -> int:

Constraints

  • 1 <= len(s) <= 10^4
  • s[i] is either '0' or '1' .

Examples

Input: s = "0100"
Output: 1

Changing the last character from '0' to '1' gives "0101", which is alternating. The string is not alternating to begin with, so at least one operation is needed.

Input: s = "10"
Output: 0

"10" is already alternating, so no operations are needed.

Input: s = "1111"
Output: 2

Both alternating strings of length 4, "0101" and "1010", differ from "1111" in two positions.