Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the longest subarray with equal numbers of 0s and 1s.
Problem: Find the length of the longest subarray with equal numbers of 0s and 1s.
def longest_eq(a):
first = {0: -1}; bal = best = 0
for i, x in enumerate(a):
bal += 1 if x else -1
if bal in first: best = max(best, i - first[bal])
else: first[bal] = i
return best
print(longest_eq([0, 1, 1, 0, 1, 1, 1, 0]), longest_eq([1, 1, 1]))What is printed?- A. 4 0
- B. 6 0
- C. 4 3
- D. 8 0
Correct answer: A. 4 0
Treat 0 as −1 and 1 as +1; equal counts mean equal running balance at both ends. Store the FIRST index of each balance (with balance 0 at index −1) to maximise length. [0, 1, 1, 0] gives 4; no longer stretch balances. All 1s never repeat a balance → 0. Overwriting with the latest index would shrink answers. O(n).
More Coding Interview Problems questions
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…
- Problem: Given n ≤ 10⁵ words, find the longest chain where each word is the previous word with exactly one letter inserted (word length ≤…