Shortest Subarray with Sum at Least K
Updated
Problem statement
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums whose sum is at least k. If no such subarray exists, return -1.
A subarray is a run of neighbouring elements of the array, for example [4,1] in [2,-3,4,1]. The values in nums can be negative.
Function
shortestSubarray(nums: int[], k: int) → intExamples
Example 1
nums = [2,-3,4,1]k = 5return = 2No single value reaches 5. The three pairs of neighbours sum to 2 + (-3) = -1, -3 + 4 = 1 and 4 + 1 = 5. The pair [4,1] reaches 5, so the answer is 2.
Example 2
nums = [1,2,3]k = 7return = -1The whole array sums to 6, which is less than 7. Every other subarray leaves out some of these positive values, so its sum is smaller still. No subarray reaches 7, so the answer is -1.
Example 3
nums = [3,-1,4,-2,5]k = 7return = 3No single value reaches 7, and the four pairs of neighbours sum to only 2, 3, 2 and 3. The three values [4,-2,5] sum to 7, so the answer is 3. A negative value inside the subarray is fine.
Constraints
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^51 <= k <= 10^9
More Oracle Onsite Interview questions
- Course ScheduleONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Minimum Meeting RoomsONSITE INTERVIEW · Seen Nov 2026
- Shortest Window with Required CountsONSITE INTERVIEW · Seen Nov 2026
- Maximum Subarray Sum with One DeletionONSITE INTERVIEW · Seen Nov 2026
- Shortest Deletion for Distinct CharactersONSITE INTERVIEW · Seen Nov 2026
- Count Dropped Rate-Limited RequestsONSITE INTERVIEW · Seen Nov 2026
- Design Authentication ManagerONSITE INTERVIEW · Seen Oct 2026
- Maximum Bouquet ValueONSITE INTERVIEW · Seen Oct 2026
- Cache an Expensive Service Across ThreadsONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Profit AnalysisVirtu Financial · OAVirtu Financial interview questions
- Minimum Size Subarray SumMicrosoft · OAMicrosoft interview questions
- Longest Run of Ones After Flipping k ZerosC3.ai · PHONE SCREENC3.ai interview questions
- Sliding Window MaximumAmazon · ONSITE INTERVIEW
- Minimum Size Subarray Sum With NegativesTekion · ONSITE INTERVIEWTekion interview questions
- Sliding Window MaximumPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Sliding Window MaximumBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Shortest Subarray with Sum at Least KApple · ONSITE INTERVIEWApple interview questions
- Longest Subarray Within an Absolute-Difference LimitGoogle · ONSITE INTERVIEWGoogle interview questions
- Roll a Weighted DieLinkedIn · ONSITE INTERVIEWLinkedIn interview questions