KatInterview

Maximum Consecutive Ones With a Single Bit Repair

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointersbinary-array

Last updated

Find the longest stretch of 1s achievable in a binary list when at most one 0 may be changed to 1, using a two-pointer window that tolerates one zero.

Maximum Consecutive Ones With a Single Bit Repair

You are given a list bits that contains only 0 and 1. You may change at most one 0 into a 1 (you may also choose to change nothing). After this optional change, look at the longest block of consecutive 1s in the list.

Return the largest block length that can be reached by choosing the change optimally.

Rules

  • Changing nothing is allowed, so a list that has no zeros simply returns its own length.
  • If every element is 0, the best you can do is change one of them, so the answer is 1.
  • If the list is empty, return 0.
  • Only the length is returned, not the position of the change.

Constraints

  • 1 <= len(bits) <= 10^5
  • Each element of bits is 0 or 1.
  • An empty list should still return 0, although the size bound above normally excludes it.

Examples

Example 1

Input: max_ones_with_one_repair([1, 0, 1, 1, 0])

Output: 4

Example 2

Input: max_ones_with_one_repair([0, 0, 0])

Output: 1

Hints

Hint 1

Think of the answer as the longest contiguous segment that contains at most one zero; that zero is the one you would change.

Hint 2

Maintain a window with two indices and a count of zeros inside it. Grow the right edge one step at a time and record the window length after each step.

Hint 3

When the zero count reaches two, advance the left edge until a zero leaves the window. Each index enters and leaves at most once, so the total work is linear.