Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA

Problem: How many subarrays of [1, 2, 2, 3] have max minus min at most 1? Run the code.

Problem: How many subarrays of [1, 2, 2, 3] have max minus min at most 1? Run the code.
a = [1, 2, 2, 3]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a) + 1) if max(a[i:j]) - min(a[i:j]) <= 1))
What is printed?
  1. A. 9
  2. B. 5
  3. C. 10
  4. D. 4

Correct answer: A. 9

The 4 singletons, the pairs [1,2], [2,2], [2,3] and the triples [1,2,2], [2,2,3] qualify; the full array has spread 2, so 9. Using < 1 keeps only equal-valued windows (5), counting all 10 subarrays ignores the condition, and requiring a spread of exactly 1 gives 4.

More Coding Interview Problems questions

Exams that ask this topic