Data Structures & AlgorithmsHardProduct-company MCQ pattern

How many contiguous subarrays of [1, 2, 3, −3, 3, 1] have sum exactly 3? (A prefix-sum + hash-map method counts them in O(n).)

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

Correct answer: A. 5

Prefix sums are 0, 1, 3, 6, 3, 6, 7, and each earlier prefix that is 3 less than a later one marks a subarray: 0 → both 3s (2), the first 3 → both 6s (2), the second 3 → the last 6 (1), total 5. They are [0..1], [0..3], [2], [2..4], [4]; missing the ones that cross the −3 gives 3 or 4.

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

Exams that ask this topic