Data Structures & AlgorithmsHard

How many contiguous subarrays of [2, 1, 3, 1, 1, 2, 4, 1] have each element sum equal to its length (sum of (a[i] − 1) over the subarray is 0)?

  1. A. 36
  2. B. 6
  3. C. 4
  4. D. 5

Correct answer: D. 5

Subtracting 1 from every element turns the condition into a zero-sum subarray of the new array, which is then a prefix-sum counting problem. Forgetting the initial prefix 0 undercounts, and the other options test a different equation.

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

Exams that ask this topic