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?
- A. 21
- B. 8
- C. 6
- 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
- Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken…
- Count the subarrays of v = [4, 6, 2, 1, 7, 3, 5, 1] whose XOR equals 0, considering only subarrays of length at least 3. Brute-force all…
- Histogram bars have heights h = [2, 1, 5, 6, 2, 3]. What is the area of the largest rectangle that fits entirely inside the histogram…
- What is the maximum sum of a non-empty subarray in the circular array [8, -8, 9, -9, 10, -11, 12], where the subarray may wrap from the…
- What is the maximum product of a non-empty contiguous subarray of [2, -5, -2, -4, 3]?
- What is the minimum number of coins needed to make an amount of 18 using unlimited coins of denominations {1, 6, 10}?