FastPrepMinimum Operations to Flip Exactly K Bits

Minimum Operations to Flip Exactly K Bits

Google logoGoogle● HardINTERNOA
Learn

Problem statement

You are given a binary array bits and an integer k.

In one operation, choose exactly k distinct indices in any positions of the array and flip their values:

  • 0 becomes 1.
  • 1 becomes 0.

Return the minimum number of operations needed to make every array element equal to 1. If this is impossible, return -1.

Function

minExactKBitFlips(bits: int[], k: int) → int

Examples

Example 1

bits = [0,0,1]k = 2return = 1

Flip the two zero-valued positions. The array becomes [1,1,1] in one operation.

Example 2

bits = [0,1,1]k = 2return = -1

Every operation flips an even number of bits, so the parity of the zero count cannot change from odd to zero.

Example 3

bits = [0,0,0,0]k = 3return = 4

Four operations suffice by omitting a different index each time. Every index is then flipped exactly three times. Fewer operations cannot satisfy both the required parity and the number of selected positions.

Example 4

bits = [1,1,1]k = 1return = 0

The array already contains only ones, so no operation is needed.

Constraints

  • 1 <= bits.length <= 10^5.
  • bits[i] is either 0 or 1.
  • 1 <= k <= bits.length.

More Google problems

See Google hiring insights
public int minExactKBitFlips(int[] bits, int k) {
    // Write your code here.
}
bits[0,0,1]
k2
expected1
Checking account…