Skip to main content

Shortest Subarray with Sum at Least K - Solution & Explanation

HardArrayBinary SearchQueueSliding Window16 min readAsked at: Amazon, Microsoft, Goldman Sachs +4
Practice this problem

Problem Statement

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.

A subarray is a contiguous part of an array.

 

Example 1:

Input: nums = [1], k = 1
Output: 1

Example 2:

Input: nums = [1,2], k = 4
Output: -1

Example 3:

Input: nums = [2,-1,2], k = 3
Output: 3

 

Constraints:

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105
  • 1 <= k <= 109

Approach Overview

Problem Overview: You are given an integer array nums and an integer k. The goal is to find the length of the shortest non‑empty subarray whose sum is at least k. The challenge comes from negative numbers in the array, which break the standard sliding window strategy used for positive-only arrays.

Approach 1: Brute Force Subarray Check (O(n²) time, O(1) space)

The most direct strategy is to examine every possible subarray. Start from each index i, keep a running sum while extending the subarray to the right, and stop once the sum becomes at least k. Track the minimum length encountered. This works because every subarray is evaluated explicitly, but the nested iteration leads to O(n²) time in the worst case. It is useful as a baseline to verify correctness and understand the structure of the problem, but it does not scale when n is large.

Approach 2: Prefix Sum + Monotonic Deque (O(n) time, O(n) space)

The optimal approach uses prefix sums and a monotonic queue. First compute a prefix array where prefix[i] stores the sum of the first i elements. Any subarray sum from i to j can then be computed as prefix[j] - prefix[i]. The goal becomes finding indices i < j where this difference is at least k while minimizing j - i.

A deque stores candidate prefix indices in increasing order of their prefix values. While iterating through the prefix array, two checks keep the structure optimal. First, if the difference between the current prefix and the front of the deque is at least k, you found a valid subarray and update the minimum length while popping from the front. Second, maintain monotonicity: if the current prefix value is smaller than the last stored prefix, remove the larger one because it will never produce a better result later. Each index enters and leaves the deque at most once, which keeps the total runtime linear.

This technique handles negative numbers gracefully and avoids the pitfalls of a standard sliding window. The combination of prefix sums and a monotonic structure ensures that only useful candidates remain in the deque during iteration.

Recommended for interviews: The prefix sum with monotonic deque solution is what interviewers expect for this problem. It demonstrates understanding of prefix transformations and efficient candidate pruning using a deque. Mentioning the brute force approach first shows you understand the search space, but implementing the O(n) solution signals strong algorithmic maturity.

Approach 1: Prefix Sum and Sliding Window with Deque

This approach uses a prefix sum array to store cumulative sums and a deque to maintain the indices of suffix values. The deque is used to efficiently find the shortest subarray with the required sum condition. For each element, we calculate the prefix sum and determine the shortest subarray that satisfies the condition using the deque.

The program calculates the prefix sum array and uses a deque to manage the indices of potential subarray starts. It iterates over each prefix sum. For each prefix sum, it checks if there's any prior prefix sum that's at least k less than the current sum. If so, it updates the potential minimum length of the subarray. After finishing the loop, if result is still INT_MAX, it returns -1 as no valid subarray exists.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), for the prefix sum array and deque.

Try this approach in the editor →

Approach 2: Brute Force Approach

Although a brute force approach will not be efficient for larger inputs, it's a good starting point to understand the combination of elements in this problem. We iterate over every starting point in the array and extend the subarray until the sum requirement is satisfied or the end of the array is reached. This ensures that we verify all possible subarray combinations.

This solution checks each subarray starting from every index. We accumulate the sum as we extend the subarray, and once we reach a sum that's at least k, we update our minimum length if this subarray is shorter than previously found subarrays. It's computationally intense and feasible only for small arrays.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2), where n is the length of the array.
Space Complexity: O(1), since we're not using additional data structures.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Prefix Sum and Sliding Window with Deque

Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), for the prefix sum array and deque.

Brute Force Approach

Time Complexity: O(n^2), where n is the length of the array.
Space Complexity: O(1), since we're not using additional data structures.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subarray EnumerationO(n²)O(1)Good for understanding the problem or very small input sizes
Prefix Sum + Monotonic DequeO(n)O(n)General optimal solution, works even with negative numbers

Video Solution

Shortest Subarray with Sum at Least K | Leetcode 862Techdose43,561 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Shortest Subarray with Sum at Least K easy or hard?
The problem is classified as Hard because negative numbers invalidate the standard sliding window technique. Solving it efficiently requires recognizing the prefix sum transformation and maintaining a monotonic deque to keep candidate starting points optimal.
Shortest Subarray with Sum at Least K Python/Java solution
Most implementations follow the same pattern: compute prefix sums, maintain a deque of candidate indices, and update the shortest length whenever the current prefix minus the front prefix is at least K. The algorithm translates directly to Python, Java, C++, or JavaScript with O(n) time complexity.
How to solve Shortest Subarray with Sum at Least K in O(n)?
Compute prefix sums so any subarray sum becomes prefix[j] - prefix[i]. Maintain a deque of indices with increasing prefix values. While iterating, remove indices from the front if the difference with the current prefix is at least K, and remove larger prefix values from the back to preserve monotonic order. This guarantees a linear scan.
What is the best approach for Shortest Subarray with Sum at Least K?
The best approach uses prefix sums combined with a monotonic deque. Prefix sums allow constant-time subarray sum queries, while the deque keeps candidate indices in increasing prefix order. This structure ensures each index is processed at most once, resulting in O(n) time complexity and O(n) space.
Is Shortest Subarray with Sum at Least K asked at Google/Amazon/Meta?
This problem pattern appears in interviews at companies like Google, Amazon, and Meta because it combines prefix sums, monotonic queues, and subarray optimization. Interviewers often use it to evaluate whether candidates can optimize beyond brute force and reason about prefix-based transformations.
What data structure is used in Shortest Subarray with Sum at Least K?
The key data structure is a deque used as a monotonic queue. It stores indices of the prefix sum array while maintaining increasing prefix values. This allows efficient removal of useless candidates and fast detection of valid subarrays.
What is the time complexity of Shortest Subarray with Sum at Least K?
The optimal solution runs in O(n) time using a prefix sum array and a monotonic deque. Each index is added and removed from the deque at most once. A naive brute force approach checks every subarray and takes O(n²) time.

Ready to solve this problem?

Practice Shortest Subarray with Sum at Least K with our built-in code editor and test cases.

Practice on FleetCode