Data Structures & AlgorithmsHardGATE CS · ICPC regional

Given an array that may contain negative numbers, which method counts the subarrays whose sum equals exactly k in O(n) expected time?

  1. A. Two pointers (sliding window)
  2. B. Prefix sums with a hash map of counts
  3. C. Binary search on the answer
  4. D. Monotonic stack

Correct answer: B. Prefix sums with a hash map of counts

Negative numbers break the monotonicity a sliding window needs, but prefix sums with counts handle any sign: each earlier equal prefix value pairs with the current one.

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

Exams that ask this topic