Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the length of the longest subarray of [1, 1, 0, 1, 1, 1, 0, 1] containing at most one zero? Run the sliding-window code.

Problem: What is the length of the longest subarray of [1, 1, 0, 1, 1, 1, 0, 1] containing at most one zero? Run the sliding-window code.
a = [1, 1, 0, 1, 1, 1, 0, 1]
l = zeros = best = 0
for r, x in enumerate(a):
    zeros += x == 0
    while zeros > 1:
        zeros -= a[l] == 0
        l += 1
    best = max(best, r - l + 1)
print(best)
What is printed?
  1. A. 3
  2. B. 8
  3. C. 6
  4. D. 5

Correct answer: C. 6

Windows with one zero: [1,1,0,1,1,1] has length 6. Allowing no zero gives 3, two zeros gives the whole array of 8, and r − l without the + 1 gives 5.

More Coding Interview Problems questions

Exams that ask this topic