Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the shortest subarray with sum at least k

Find the minimal-length contiguous subarray whose sum is >= k (supports negative numbers).

Python practice25 minArrays – Fundamentals & PatternsAdvancedLast updated March 25, 2026

Problem statement

Given an integer array nums (may contain negative numbers) and an integer k, return the length of the shortest, non-empty, contiguous subarray of nums with sum at least k. If no such subarray exists, return -1. This problem requires handling negative values and should be solved using prefix sums plus a monotonic queue for optimal performance.

Task

Use prefix sums and a monotonic deque to compute the shortest subarray with sum at least k in O(n) time.

Examples

Small example with negatives

Input

nums = [2, -1, 2], k = 3

Output

3

The whole array sums to 3, length is 3.

Input format

Function signature: shortest_subarray_with_sum_at_least_k(nums: list[int], k: int) -> int

Output format

Return an integer: the minimal length of a contiguous subarray with sum >= k, or -1 if none exists.

Constraints

1 <= len(nums) <= 10^5 for typical inputs, -10^9 <= nums[i] <= 10^9, -10^14 <= k <= 10^14. Expected O(n) time and O(n) extra space.

Samples

Sample 1

Input

nums = [1, 2, 3, 4, 5], k = 11

Output

3

Subarray [3,4,5] sums to 12 and is minimal length 3.