Minimum Changes To Make Alternating Binary String

You are given a string s of 0s and 1s. In one operation you can change any character to the other bit. A string is alternating if no two adjacent characters are equal, such as "010" or "1010". Return the minimum number of operations needed to make s alternating.

30:00

Minimum Changes To Make Alternating Binary String
easy
Free written solution
Topics
Companies

You are given a string s of 0s and 1s. In one operation you can change any character to the other bit. A string is alternating if no two adjacent characters are equal, such as "010" or "1010". Return the minimum number of operations needed to make s alternating.

Example 1:
Input: {"s":"0100"}
Output: 1
Constraints:
  • 1≤s.length≤1041 \leq s.length \leq 10^4

  • s[i] is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"0100"}

Only two alternating strings of length 4 exist: one starting with 0 and one starting with 1. Count how far s is from the first; the second is its exact opposite.

s against both alternating patterns

0101

0
1
0
1

s

0
1
0
0

1010

1
0
1
0

0

1

2

3

Red cells are positions that would have to change. At every position exactly one pattern disagrees with s.

changes needed (0 of 4 scanned)

to 0101...

0

to 1010...

0

Variables
VariableValue
count0
DepthFunction Call
Stack empty
0/6