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?- A. 3 3 5
- B. 3 2 5
- C. 4 2 5
- 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
- Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another…
- Problem: Find how many numbers in 1..n have all distinct digits — the digit-DP-free shortcut for n = 10ᵏ uses counting. python def…
- Problem: Find the minimum window length in which every one of k distinct product IDs appears at least once (k = number of distinct values…
- Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally). python def steps(n)…
- Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS). python from collections import deque…
- Problem: Count the inversions of an array with merge sort. python def inv(a): if len(a) < 2: return a, 0 m = len(a) // 2 L, x =…