Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many subarrays of [1, 2, 3, 1, 2, 3, 4] contain exactly 3 distinct values? Run the brute-force code.

Problem: How many subarrays of [1, 2, 3, 1, 2, 3, 4] contain exactly 3 distinct values? Run the brute-force code.
a = [1, 2, 3, 1, 2, 3, 4]
print(sum(1 for i in range(len(a)) for j in range(i, len(a)) if len(set(a[i:j + 1])) == 3))
What is printed?
  1. A. 11
  2. B. 24
  3. C. 15
  4. D. 5

Correct answer: A. 11

Exactly 3 distinct values: 11 subarrays. 'At most 3' gives 24, 'at least 3' gives 15, and length exactly 3 gives 5; the sliding-window trick computes at-most(3) − at-most(2) = 24 − 13 = 11.

More Coding Interview Problems questions

Exams that ask this topic