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?- A. 3
- B. 8
- C. 6
- 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
- Problem: How many distinct products a b arise when a and b are each a face value from 1 to 6? Run the code. python print(len({a b for a in…
- Problem: How many subsets of {1, 2, ..., 6} have a product that is a perfect square? Run the code (the empty set has product 1). python…
- Problem: What is the number of distinct values of floor(n / 2) + floor(n / 3) for 1 <= n <= 50? Run the code. python print(len({n // 2 + n…
- Problem: What is the largest sum of a subarray of length at least 2 in [4, -1, 5, -6, 3, 2]? Run the code. python a = [4, -1, 5, -6, 3, 2]…
- Problem: How many paths of length exactly 4 go from vertex 0 to vertex 0 in the complete graph K3? Run the code (walks allowed to repeat…
- Problem: How many ways are there to choose 4 distinct numbers from 1..12 with sum 26? Run the code. python from itertools import…