Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable.
Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable.
def longest_ones(a, k):
l = zeros = best = 0
for r, x in enumerate(a):
zeros += x == 0
while zeros > k:
zeros -= a[l] == 0
l += 1
best = max(best, r - l + 1)
return best
print(longest_ones([1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1], 2))What is printed?- A. 7
- B. 6
- C. 5
- D. 3
Correct answer: A. 7
Keep at most k zeros in the window and shrink from the left when a third zero enters. The best window is indices 2..8 = [1, 1, 0, 0, 1, 1, 1], length 7. Using r − l (forgetting + 1) prints 6, shrinking when zeros ≥ k allows only one flip (5), and ignoring flips gives the plain longest run 3.
More Coding Interview Problems questions
- Problem: Return the maximum of every window of size k in a stream of readings. python from collections import deque def winmax(a, k): dq…
- Problem: For n = 10⁶ readings and window size k = 10⁵, report every window maximum. Which approach fits the limits best?
- Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters. python def countdistinct(s, k): freq, c…
- Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters…
- Problem: Return the smallest window of s that contains every character of t (with multiplicity). python from collections import Counter…
- Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case…