Data Structures & AlgorithmsHardProduct Company SDE · prefix-count OA
Problem: How many contiguous subarrays of [1, 2, 1, 2, 1, 3, 1] contain exactly 2 odd numbers?
Problem: How many contiguous subarrays of [1, 2, 1, 2, 1, 3, 1] contain exactly 2 odd numbers?
a = [1, 2, 1, 2, 1, 3, 1]
k = 2
cnt = 0
for i in range(len(a)):
for j in range(i, len(a)):
if sum(x % 2 for x in a[i:j + 1]) == k:
cnt += 1
print(cnt)What is printed?- A. 19
- B. 16
- C. 7
- D. 6
Correct answer: C. 7
The brute force counts subarrays with exactly k = 2 odd values: 7. The linear method counts prefix-odd-count pairs differing by k, or uses atMost(2) − atMost(1). Counting 'at most 2' gives 19, 'at least 2' gives 16, and slicing a[i:j] instead of a[i:j + 1] drops the last element and gives 6.
More Coding Interview Problems questions
- Problem: How many subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum of exactly 10? python cnt = 0 for m in range(1 << 8): if sum(i + 1 for i…
- Problem: After running Floyd-Warshall on a directed graph with possibly negative edges, which check correctly detects that vertex i lies…
- Problem: A road graph has V = 10^5 vertices and E = 3 10^5 edges, all weights non-negative, and you need shortest paths from one source…
- Problem: For the shortest subarray with sum at least S in an array of positive integers, a two-pointer sweep is used: extend the right…
- Problem: Weighted interval scheduling (each job has a start, finish and profit; choose a set of non-overlapping jobs to maximise profit)…
- Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from…