Data Structures & AlgorithmsVery hardProduct company OA

How many contiguous subarrays of [1, 3, 2, 4, 6, 5] satisfy max − min ≤ 2? (Two monotonic deques shrink the window from the left.)

  1. A. 21
  2. B. 8
  3. C. 14
  4. D. 15

Correct answer: C. 14

Valid windows ending at each right end: 1, 2, 3, 3, 2, 3, total 14. Because a valid window stays valid when shrunk, the two-pointer window adds (r − l + 1) per step. 8 uses spread < 2 instead of ≤ 2, 15 uses spread ≤ 3 and 21 counts every subarray.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic