Skip to main content
Back to problems
Leetcode
Hard
Arrays
Queues
Ordered Structures
Google
Meta
Amazon
Shortest Subarray With Sum at Least K

Find the length of the shortest contiguous subarray whose sum is at least k. The array may contain negative numbers.

Acceptance 0%
Problem Statement

Shortest Subarray With Sum at Least K

Given an integer array nums and an integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k.

The array can contain positive, negative, or zero values. If no such subarray exists, return -1.

This problem is tricky because a simple sliding window does not work reliably when negative numbers are allowed.

Input Format

  • A single integer array nums.
  • A single integer k.

Output Format

  • Return an integer: the minimum length of a non-empty contiguous subarray with sum at least k, or -1 if none exists.

Constraints

  • 1 <= nums.length
  • Elements of nums may be negative, zero, or positive.
  • k may be positive, zero, or negative.
  • Find the shortest valid contiguous subarray.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

3

Explanation

The whole array sums to 3, so the shortest valid subarray has length 3.

Example 2

Input

nums = [1, 2], k = 4

Output

-1

Explanation

No contiguous subarray has sum at least 4.

Show 1 more example

Example 3

Input

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

Output

1

Explanation

The subarray [5] has sum 5, which is at least 3, and its length is 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.