FastPrepCount Prioritized Binary-Run Operations

Count Prioritized Binary-Run Operations

ZipRecruiter logoZipRecruiter● MediumNEW GRADOA
Learn

Problem statement

bits consists of zero or more 1s followed by zero or more 0s, and k >= 2. Repeatedly apply the first available rule:

  1. If at least k zeros exist, remove the last k zeros and prepend one 1.
  2. Otherwise, if a 1 exists, replace the last 1 with 0.

Stop when neither rule applies and return the number of operations.

Function

countBinaryOperations(bits: String, k: int) → long

Examples

Example 1

bits = "10"k = 2return = 3

The states by counts are (1,1), (0,2), (1,0), and (0,1).

Example 2

bits = "00"k = 2return = 2

Compress two zeros to one 1, then convert that 1 to one zero.

Constraints

  • 1 <= bits.length <= 100000
  • 2 <= k <= 100000
  • The operation count fits in signed 64-bit.

More ZipRecruiter problems

See ZipRecruiter hiring insights
public long countBinaryOperations(String bits, int k) {
    // Write your code here.
}
bits"10"
k2
expected3
Checking account…