Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA
Problem: The longest subarray with equally many 0s and 1s of a = [0, 1, 0, 0, 1, 1, 0] is needed. Run the prefix-balance code and print the length.
Problem: The longest subarray with equally many 0s and 1s of a = [0, 1, 0, 0, 1, 1, 0] is needed. Run the prefix-balance code and print the length.
a = [0, 1, 0, 0, 1, 1, 0]
first = {0: -1}
s = 0
best = 0
for i, x in enumerate(a):
s += 1 if x else -1
if s in first:
best = max(best, i - first[s])
else:
first[s] = i
print(best)What is printed?- A. 6
- B. 4
- C. 2
- D. 7
Correct answer: A. 6
The subarray a[0..5] = [0,1,0,0,1,1] has three 0s and three 1s. Storing only the first occurrence of each balance gives the longest span between equal balances.
More Coding Interview Problems questions
- Problem: Find the 3 smallest pair sums from A = [1, 7, 11] and B = [2, 4, 6], using a heap that starts with each A element paired with…
- Problem: An undirected connected graph has an Euler circuit (a closed walk using every edge exactly once) if and only if which condition…
- Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2…
- Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4? python a = [1, 2, 3, 4, 5, 6, 7] print(sum(1…
- Problem: Count the subarrays of a = [10, 5, 2, 6] whose product is strictly less than k = 100. python def cnt(a, k): if k <= 1: return 0 p…
- Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below. python def dsub(s): dp = [1] last =…