Shortest Subarray with Sum at Least K

HardSliding Windowmonotonic queue

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums (which may contain negative numbers) and an integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k. If no such subarray exists, return -1. Because of negative values, a plain two-pointer window does not work. Aim for O(n) time.

Examples

Input: nums = [1], k = 1
Output: 1
The single element already sums to 1.
Input: nums = [1,2], k = 4
Output: -1
The largest possible sum is 3.
Input: nums = [2,-1,2], k = 3
Output: 3
Only the whole array reaches a sum of 3.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5
  • 1 <= k <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic queue problems