Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA
Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code.
Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code.
from collections import Counter
a = [4, 1, -1, 2, 3]
c = Counter({0: 1})
s = ans = 0
for x in a:
s = (s + x) % 4
ans += c[s]
c[s] += 1
print(ans)What is printed?- A. 6
- B. 5
- C. 7
- D. 4
Correct answer: D. 4
Equal prefix residues mod 4 mark subarrays whose sum is divisible by 4, and the hash-map count of such pairs is 4.
More Coding Interview Problems questions
- Problem: How many distinct substrings of length 2 does 'abcabc' contain? Run the code. python s = 'abcabc' print(len({s[i:i + 2] for i in…
- Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code. python s = ')()())'…
- Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code. python tokens = '2 1 + 3 '.split() st = [] for…
- Problem: What is the maximum matching size in the bipartite graph with left vertices {0,1,2}, right vertices {0,1,2} and edges (0,0)…
- Problem: How many integers x in [1, 100] satisfy x^2 ≡ 1 (mod 8)? Run the code. python print(sum(1 for x in range(1, 101) if (x x) % 8 ==…
- Problem: What is the smallest positive integer x with x ≡ 1 (mod 4) and x ≡ 2 (mod 5)? Run the code. python print(next(x for x in range(1…