FastPrepMinimum Nonadjacent Flips for an Alternating Binary String

Minimum Nonadjacent Flips for an Alternating Binary String

Infosys logoInfosys● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

You are given a non-empty binary string. In one operation, flip one bit. Across the entire transformation, no two flipped positions may be adjacent.

Return the minimum operations needed to make the string alternate between 0 and 1. Return -1 when neither alternating target can be reached under the nonadjacent-operation rule.

Function

minNonAdjacentFlips(bits: String) → int

Examples

Example 1

bits = "111101"return = 2

Flipping positions 0 and 2 produces 010101; the flipped positions are not adjacent.

Example 2

bits = "1001"return = -1

One target requires adjacent flips at positions 0 and 1, and the other requires adjacent flips at positions 2 and 3.

Constraints

  • 1 <= bits.length <= 200000
  • bits contains only 0 and 1.

Source note: Interview prompt excerpt preserved as source evidence.

More Infosys problems

See Infosys hiring insights
public int minNonAdjacentFlips(String bits) {
    // Write your code here.
}
bits"111101"
expected2
Checking account…