Data Structures & AlgorithmsHardGATE CS · TCS NQT

How many contiguous subarrays of [1, -1, 2, -2, 3, -3, 1] sum to exactly 1?

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

Correct answer: B. 7

Prefix sums with a hashmap count pairs whose difference is 1, with prefix 0 seeded: 7. Forgetting the seed drops the subarrays that start at index 0 (5); a sliding window, invalid with negatives, finds 3, and 2 counts only the single elements equal to 1.

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

Exams that ask this topic