Minimum Number of Flips to Make The Binary String Alternating

Medium Topics Company Tags

You may perform these operations on the binary string s in any order:

  • Move its first character to the end. This rotation is free.
  • Flip any one character, changing 0 to 1 or 1 to 0.

Return the fewest flips needed to make the string alternating, meaning every pair of adjacent characters differs. Only flips are counted; you may perform any number of rotations. The first and last characters do not need to differ.

Example 1:

Input: s = "001"

Output: 0

Explanation: Move the first 0 to the end to obtain 010. This is already alternating, so the rotation needs no flips.

Example 2:

Input: s = "0001"

Output: 1

Explanation: Flip the second character to obtain 0101. No rotation of 0001 is alternating, so one flip is necessary.

Example 3:

Input: s = "0000"

Output: 2

Explanation: Flip the second and fourth characters to obtain 0101. Any alternating string of length four needs two ones, so two flips are necessary.

Constraints:

  • 1 <= s.length <= 100000
  • Every character is 0 or 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.