Data Structures & AlgorithmsModerateCodeforces Div2 C/D · Amazon SDE OA

Array d = [1, 2, 1, 3, 4, 3, 5]. Count the contiguous subarrays containing exactly three distinct values. Run the brute-force code.

Array d = [1, 2, 1, 3, 4, 3, 5]. Count the contiguous subarrays containing exactly three distinct values. Run the brute-force code.
d=[1,2,1,3,4,3,5]
n=len(d)
print(sum(1 for i in range(n) for j in range(i,n) if len(set(d[i:j+1]))==3))
What is printed?
  1. A. 21
  2. B. 8
  3. C. 6
  4. D. 3

Correct answer: C. 6

Each subarray is tested for exactly three distinct values. Testing exactly two counts a neighbouring class, at most three admits fewer distinct values, and requiring length three or more drops valid two-element windows that happen to have three values.

More Coding Interview Problems questions

Exams that ask this topic