Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain.

Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain.
def after_delete(a):
    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)
    return best
print(after_delete([1, 1, 0, 1]), after_delete([1, 1, 1]), after_delete([0, 1, 1, 1, 0, 1, 1, 0, 1]))
What is printed?
  1. A. 3 3 5
  2. B. 3 2 5
  3. C. 4 2 5
  4. D. 3 2 6

Correct answer: B. 3 2 5

Window with at most one zero; its length minus one (the deleted element) is r − l. Even with no zero you must delete something, so [1, 1, 1] gives 2. The last array's best window [1, 1, 1, 0, 1, 1] → 5. O(n).

More Coding Interview Problems questions

Exams that ask this topic