Data Structures & AlgorithmsHardTCS NQT · Product Company OA

Problem: How many subarrays of [2, 3, 4, 5] contain exactly one odd number? Run the code.

Problem: How many subarrays of [2, 3, 4, 5] contain exactly one odd number? Run the code.
a = [2, 3, 4, 5]
print(sum(1 for i in range(4) for j in range(i + 1, 5) if sum(x % 2 for x in a[i:j]) == 1))
What is printed?
  1. A. 8
  2. B. 4
  3. C. 6
  4. D. 10

Correct answer: C. 6

Odd values sit at indices 1 and 3: subarrays with only the first odd number are 4 and with only the second are 2, so 6. Counting 'at least one odd' gives 8, a bound of range(i + 1, 4) never includes the last element (4), and 10 counts all subarrays.

More Coding Interview Problems questions

Exams that ask this topic