Data Structures & AlgorithmsHardProduct Company SDE · CP practice
Problem: How many subarrays of [1, -1, 1, -1, 1] have sum 0? Run the prefix-count code.
Problem: How many subarrays of [1, -1, 1, -1, 1] have sum 0? Run the prefix-count code.
from collections import Counter
a = [1, -1, 1, -1, 1]
c = Counter({0: 1})
s = ans = 0
for x in a:
s += x
ans += c[s]
c[s] += 1
print(ans)What is printed?- A. 4
- B. 3
- C. 6
- D. 15
Correct answer: C. 6
Prefix sums 0, 1, 0, 1, 0, 1 hold 0 three times and 1 three times, so C(3,2) + C(3,2) = 6. Not seeding the Counter with {0: 1} gives 4, counting only prefix value 0 gives 3, and 15 is all subarrays.
More Coding Interview Problems questions
- Problem: What is the number of paths from (0,0) to (4,4) using right and up moves that never touch the diagonal cells (i, i) except at the…
- Problem: What is the number of integers in [1, 10000] that are perfect squares and also end in the digit 9? Run the code. python…
- Problem: How many ways are there to split the string '1234' into two non-empty parts whose integer values are both divisible by 3? Run the…
- Problem: How many non-empty subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum that is a multiple of 4? Run the code. python from itertools…
- Problem: What is the minimum number of operations to make the array [5, 1, 4] strictly increasing where one operation increments any…
- Problem: What is the number of integers in [1, 999] whose digit product is 0? Run the code. python print(sum(1 for x in range(1, 1000) if…