KatInterview

Minimum Length Subarray with Sum Threshold

Stacks & QueuesAuto-graded · 24 test cases
MediumAuto-gradedStacks & Queuesprefix-sumsmonotonic-dequesliding-window

Last updated

Tests the ability to optimize subarray sum queries using prefix sums and monotonic deque when values can be negative.

You are given an array of integers values (which may include negative numbers) and an integer threshold.

Your task is to find the length of the shortest contiguous subarray whose sum is greater than or equal to threshold. If no such subarray exists, return -1.

A subarray must contain at least one element.

Constraints

  • 1 <= len(values) <= 200,000
  • -10^9 <= values[i] <= 10^9
  • -10^9 <= threshold <= 10^9
  • The subarray must be non-empty

Examples

Example 1

Input: min_subarray_sum_threshold([2, -1, 2], 3)

Output: 3

Example 2

Input: min_subarray_sum_threshold([1, 2, 3, 4, 5], 11)

Output: 3

Example 3

Input: min_subarray_sum_threshold([1, 2], 4)

Output: -1

Example 4

Input: min_subarray_sum_threshold([-2, -1, 2, 1], 1)

Output: 1

Hints

Hint 1

Consider using cumulative sums to quickly compute subarray totals between any two positions.

Hint 2

A monotonic deque can help track promising starting positions while maintaining useful ordering properties.

Hint 3

Each position should enter and leave your data structure at most once to achieve linear time complexity.