Data Structures & AlgorithmsHardGATE CS · TCS NQT

Which technique detects whether an array contains a non-empty subarray with sum zero in O(n) expected time?

  1. A. Sorting the array and binary search for zero
  2. B. Two pointers from both ends
  3. C. Dynamic programming over all subarrays
  4. D. Prefix sums stored in a hash set (repeat means a zero-sum subarray)

Correct answer: D. Prefix sums stored in a hash set (repeat means a zero-sum subarray)

If two prefix sums are equal, the elements between them sum to zero. Checking prefix sums against a hash set finds any such repeat in one pass.

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

Exams that ask this topic