Ctrl K

Flip the Head or the Tail

Medium
You are given a string bits of length n made of 0 and 1. Two operations are allowed: - pick an index i and invert every character from position 0 through i, at a cost of i + 1; - pick an index i and invert every character from position i through n - 1, at a cost of n - i. Inverting a character turns 0 into 1 and vice versa. Return the minimum total cost of making all characters of the string the same.
Example 1
bits="1100" → 2

Flip the tail starting at position 2 for 4 − 2 = 2 and get 1111.

Example 2
bits="10110" → 4

Flip the head up to position 0 for 1 (00110), the tail from position 4 for 1 (00111), the head up to position 1 for 2 (11111). Total 4.

Example 3
bits="0" → 0
Constraints
  • 1 ≤ len(bits) ≤ 10⁵
  • bits contains only 0 and 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBrackets With Wildcards MediumBead String Without Twins MediumAlternate After Rotating MediumWells Beside the Houses MediumBinary Number Under a Cap Medium
loading Python…
Input
bits="1100"
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 165 tests on the server, hidden ones included.