Data Structures & AlgorithmsHardProduct company OA
Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts.
Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts.
def odd_sum_subarrays(a):
even, odd, run, res = 1, 0, 0, 0
for x in a:
run += x
if run % 2:
res += even; odd += 1
else:
res += odd; even += 1
return res
print(odd_sum_subarrays([7, 2, 9, 4]), odd_sum_subarrays([8, 8]), odd_sum_subarrays([1, 1, 1, 1, 1]))What is printed?- A. 6 0 9
- B. 6 1 9
- C. 4 0 9
- D. 6 0 6
Correct answer: A. 6 0 9
A subarray (i, j] has an odd sum exactly when prefix[j] and prefix[i] have different parity, so pair each odd prefix with earlier even prefixes (the empty prefix counts as even – hence even = 1) and vice versa. [7, 2, 9, 4]: prefixes 7, 9, 18, 22 → 1 + 1 + 2 + 2 = 6 of the 10 subarrays. Five 1s: prefixes 1..5 → 1 + 1 + 2 + 2 + 3 = 9. Starting even at 0 forgets subarrays that begin at index 0. O(n).
More Coding Interview Problems questions
- Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid…
- Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window. python def…
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…