Data Structures & AlgorithmsVery hardProduct company OA
Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1.
Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1.
def bounded_max(a, L, R):
def at_most(b):
res = run = 0
for x in a:
run = run + 1 if x <= b else 0
res += run
return res
return at_most(R) - at_most(L - 1)
print(bounded_max([3, 1, 6, 2, 4], 3, 5), bounded_max([1, 1, 2], 2, 2))What is printed?- A. 6 3
- B. 4 3
- C. 4 1
- D. 2 3
Correct answer: B. 4 3
at_most(b) counts subarrays made only of values ≤ b: every run of length r contributes r subarrays ending at each position. [3, 1, 6, 2, 4]: at_most(5) = 1 + 2 + 0 + 1 + 2 = 6, at_most(2) = 0 + 1 + 0 + 1 + 0 = 2 → 4 ([3], [3, 1], [4], [2, 4]). [1, 1, 2]: 6 − 3 = 3 (every subarray containing the 2). Counting only subarrays whose every element lies in [L, R] would miss [3, 1] and [2, 4]. O(n).
More Coding Interview Problems questions
- Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is…
- Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and…
- Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x…
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…
- Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings. python def…
- Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack. python def…