FastPrepShortest Subarray with Sum at Least K

Shortest Subarray with Sum at Least K

Apple logoApple● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Return the length of the shortest nonempty contiguous subarray of nums whose sum is at least k. Return -1 if none exists.

Both the array values and k may be negative, zero, or positive. An empty input has no nonempty subarray.

Function

shortestSubarray(nums: int[], k: int) → int

Examples

Example 1

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

Only the whole array reaches sum three.

Example 2

nums = [1,2]k = 4return = -1

No nonempty range reaches four.

Constraints

  • 0 <= nums.length <= 10^5.
  • -10^9 <= nums[i], k <= 10^9.
  • Use signed 64-bit or wider arithmetic for prefix sums.

More Apple problems

See Apple hiring insights
public int shortestSubarray(int[] nums, int k) {
    // Write your solution here.
}
nums[2,-1,2]
k3
expected3
Checking account…