Data Structures & AlgorithmsVery hardCodeforces Div2 D · LeetCode-style

What is the length of the shortest contiguous subarray of [2, -1, 2, 3, -4, 5, 1] whose sum is at least 6? Negative numbers are present, and if no subarray works, the answer is −1.

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

Correct answer: B. 2

With negative numbers a shrinking window can discard a valid start. Use prefix sums with a monotone deque: for each end, pop starts whose prefix is no larger than the current prefix, and check the smallest valid start greedily.

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

Exams that ask this topic