Skip to main content
Back to problems
Leetcode
Medium
Strings
Arrays
Greedy
Minimum Number Of Flips To Make The Binary String Alternating

Find the minimum number of single-character flips needed to make a binary string alternating.

Acceptance 0%
Problem Statement

You are given a binary string ss consisting only of '0' and '1'.

In one operation, you may flip any single character: change '0' to '1' or '1' to '0'.

Return the minimum number of flips required to make the string alternating, meaning no two adjacent characters are the same.

A valid alternating string can start with either '0' or '1'. Choose the cheaper of the two possibilities.

Input Format

  • A binary string s.
  • s contains only characters '0' and '1'.

Output Format

  • Return an integer: the minimum number of flips needed to transform s into an alternating string.

Constraints

  • 1 <= |s| <= $10^{5}$
  • s[i] ∈ {'0','1'}
  • Exactly one character may be flipped per operation.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "0100"

Output

1

Explanation

Two alternating targets are 0101 and 1010. The string 0100 differs from 0101 in one position, so the minimum number of flips is 1.

Example 2

Input

s = "10"

Output

0

Explanation

10 is already alternating, so no flips are needed.

Show 1 more example

Example 3

Input

s = "1111"

Output

2

Explanation

The closest alternating strings are 0101 and 1010. Each differs from 1111 in two positions, so the answer is 2.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.