Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

Array a = [2, -1, 3, 1, -2, 4]. How many contiguous subarrays have a sum equal to their length? Subtract 1 from each element first and count zero-sum subarrays with prefix sums.

  1. A. 7
  2. B. 6
  3. C. 4
  4. D. 0

Correct answer: B. 6

Subtracting 1 from every element turns the condition into sum(a_i - 1) = 0 over the subarray, and then prefix sums with a hash map count the zero-sum windows. Counting zero-sum subarrays of the original array is a different quantity.

More Coding Interview Problems questions

Exams that ask this topic