Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative.
Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative.
def count_k(a, k):
seen = {0: 1}
p = ans = 0
for x in a:
p += x
ans += seen.get(p - k, 0)
seen[p] = seen.get(p, 0) + 1
return ans
print(count_k([1, -1, 1, -1, 1], 1))What is printed?- A. 3
- B. 4
- C. 5
- D. 6
Correct answer: D. 6
Prefix sums are 1, 0, 1, 0, 1 (starting from 0). Each time p − 1 has been seen c times, c subarrays end here: 1 + 0 + 2 + 0 + 3 = 6. Without the initial {0: 1}, subarrays starting at index 0 are missed (answer 3). A sliding window fails because of the negatives. O(n).
More Coding Interview Problems questions
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…