Data Structures & AlgorithmsHardProduct Company SDE · CP practice
Problem: What is the length of the longest subarray of [1, 2, -3, 3, -1, -2] whose sum is zero? Run the prefix-sum code.
Problem: What is the length of the longest subarray of [1, 2, -3, 3, -1, -2] whose sum is zero? Run the prefix-sum code.
a = [1, 2, -3, 3, -1, -2]
first = {0: -1}
s = 0
best = 0
for i, x in enumerate(a):
s += x
if s in first:
best = max(best, i - first[s])
else:
first[s] = i
print(best)What is printed?- A. 3
- B. 4
- C. 7
- D. 6
Correct answer: D. 6
The whole array sums to 0 (prefix 0 at index 5 matches the seed at −1), so the length is 6. Without the {0: −1} seed it is 3, 4 counts the zero-sum subarrays, and adding + 1 to i − first[s] gives 7.
More Coding Interview Problems questions
- Problem: How many integers in [1, 100] are sums of two positive cubes? Run the code. python print(len({a 3 + b 3 for a in range(1, 5) for…
- Problem: How many distinct sums of two different elements of [1, 2, 4, 8] are there? Run the code. python from itertools import…
- Problem: How many ways are there to place 2 non-attacking rooks on a 4 x 4 board? Run the code. python from itertools import combinations…
- Problem: How many integers in [1, 1000] have exactly three distinct decimal digits? Run the code. python print(sum(1 for x in range(1…
- Problem: How many primes p <= 200 have p + 6 also prime? Run the code. python def isp(n): return n > 1 and all(n % d for d in range(2…
- Problem: How many integers in [1, 2000] have an odd number of positive divisors? Run the code. python print(sum(1 for x in range(1, 2001)…