Implement the shortestSubarrayAtLeastKLength method that returns the shortest subarray length with sum at least k.

You are given an integer array that may contain positive, zero, and negative values. Return the length of the shortest continuous subarray whose sum is at least k.

If no such subarray exists, return -1. Because negative values are allowed, a normal two-pointer window is not enough.

Example 1

Input
nums (int[]) = [2,-1,2]
size (int) = 3
k (int) = 3
Returns (int) 3

Example 2

Input
nums (int[]) = [1,2]
size (int) = 2
k (int) = 4
Returns (int) -1

Example 3

Input
nums (int[]) = [84,-37,32,40,95]
size (int) = 5
k (int) = 167
Returns (int) 3

Use prefix sums and a monotonic deque.

For each prefix sum, check whether subtracting the smallest useful previous prefix gives a sum of at least k. When it does, update the answer and remove that previous prefix because a later prefix can give a shorter length.

Maintain the deque in increasing order of prefix sums. If the current prefix is smaller than or equal to the last stored prefix, the last one is no longer useful.

Pseudocode:

function shortestSubarrayAtLeastKLength(nums, size, k):
    prefix[0] = 0
    for i from 0 to size - 1:
        prefix[i + 1] = prefix[i] + nums[i]
    deque = empty deque of indexes
    answer = infinity
    for i from 0 to size:
        while deque is not empty and prefix[i] - prefix[deque.front] >= k:
            answer = min(answer, i - deque.front)
            remove front from deque
        while deque is not empty and prefix[i] <= prefix[deque.back]:
            remove back from deque
        add i to back of deque
    if answer is infinity:
        return -1
    return answer
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.