Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts).
Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts).
def count(a, k):
seen, s, res = {0: 1}, 0, 0
for x in a:
s += x
res += seen.get(s - k, 0)
seen[s] = seen.get(s, 0) + 1
return res
print(count([3, 4, -7, 1, 3, 3, 1, -4], 7))What is printed?- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: B. 4
Prefix sums are 0, 3, 7, 0, 1, 4, 7, 8, 4. For each prefix P, add how many earlier prefixes equal P − 7: the first 7 matches one 0, the second 7 matches two 0s, and 8 matches the 1, for a total of 4. A two-pointer window fails here because negatives break monotonicity.
More Coding Interview Problems questions
- Search for a value in a sorted array that was rotated and MAY CONTAIN DUPLICATES (e.g. [1, 1, 1, 1, 0, 1, 1]). What is the worst-case time…
- Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n). python def peak(a)…
- Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and…
- Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass. python class N: def init(s, v, nx=None)…
- Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order. python class N: def…
- Deep-copy a linked list whose nodes also have a random pointer. Which approach uses O(n) time and only O(1) extra space (besides the…