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?
  1. A. 6 3
  2. B. 4 3
  3. C. 4 1
  4. 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

Exams that ask this topic