Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA

Problem: Using at most one flip of a 0 to 1, what is the longest run of consecutive 1s in [1, 0, 1, 1, 0, 1]? Run the sliding-window code.

Problem: Using at most one flip of a 0 to 1, what is the longest run of consecutive 1s in [1, 0, 1, 1, 0, 1]? Run the sliding-window code.
a = [1, 0, 1, 1, 0, 1]
l = best = zeros = 0
for r, x in enumerate(a):
    if x == 0:
        zeros += 1
    while zeros > 1:
        if a[l] == 0:
            zeros -= 1
        l += 1
    best = max(best, r - l + 1)
print(best)
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

Flipping the 0 at index 4 gives the run 1,1,1,1 at indices 2 to 5, of length 4. The window tracks at most one zero.

More Coding Interview Problems questions

Exams that ask this topic