FastPrepShortest Subarray with Sum at Least K

Shortest Subarray with Sum at Least K

Google logoGoogle● HardNEW GRADPHONE SCREEN
Learn

Problem statement

Given an integer array nums and an integer k, return the length of the shortest nonempty contiguous subarray whose sum is at least k. Return -1 if no such subarray exists.

Values may be negative. A subarray is a contiguous part of the array.

Function

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

Examples

Example 1

nums = [1]k = 1return = 1

The single-element subarray has sum 1.

Example 2

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

Even the sum of the entire array is below 4.

Example 3

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

Only the entire array reaches a sum of 3.

Constraints

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

More Google problems

See Google hiring insights
public int shortestSubarray(int[] nums, int k) {
    // Write your code here
}
nums[1]
k1
expected1
Checking account…