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

Array a = [1, -2, 3, 2, -1, 4, -3, 2]. What is the length of the longest contiguous subarray whose sum is exactly 4?

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

Correct answer: A. 7

Store the FIRST index of each prefix sum; at j look up prefix − 4. The longest hit is indices 0..6, [1, −2, 3, 2, −1, 4, −3], with sum 4 and length 7. The shortest such subarray is [4] (1), there are 5 such subarrays in total, and 8 would need the whole array, whose sum is 6.

More Coding Interview Problems questions

Exams that ask this topic