Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts.
Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts.
def nice(a, k):
cnt = {0: 1}; odd = res = 0
for x in a:
odd += x & 1
res += cnt.get(odd - k, 0)
cnt[odd] = cnt.get(odd, 0) + 1
return res
print(nice([2, 2, 2, 1, 2, 2, 1, 2, 2, 2], 2), nice([1, 1, 2, 1, 1], 3))What is printed?- A. 12 2
- B. 16 3
- C. 9 2
- D. 16 2
Correct answer: D. 16 2
Map each element to 1 if odd and count subarrays with sum k – the same prefix-sum trick. In the first array, the block between the two odd numbers can extend 4 positions to the left and 4 to the right: 4 × 4 = 16. Second: [1,1,2,1] and [1,2,1,1]. O(n).
More Coding Interview Problems questions
- Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums). python from…
- Problem: Given n meetings with values, choose non-overlapping ones (end < next start) to maximise total value – weighted interval…
- Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or…
- Problem: Count the distinct BST shapes that store keys 1..n. python def shapes(n): dp = [1] + [0] n for k in range(1, n + 1): dp[k] =…
- Problem: Count the number of ways to tile a 2 × n board with 2 × 1 dominoes, modulo 10⁹ + 7. cpp const long long MOD = 1e9 + 7; long long…
- Problem: Find the minimum number of perfect squares that sum to n. python def squares(n): dp = [0] + [float('inf')] n for i in range(1, n…