Shortest Subarray with Sum at Least K
Updated
Problem statement
You are given an integer array nums and an integer k. A subarray is a nonempty run of elements that sit next to each other in nums. Find the shortest subarray whose sum is at least k, and return its length. Return -1 if no such subarray exists.
The values in nums and k itself may be negative, zero, or positive. An empty array has no subarray at all.
Function
shortestSubarray(nums: int[], k: int) → intExamples
Example 1
nums = [2,-1,2]k = 3return = 3Every shorter subarray sums to less than three. The whole array sums to exactly three, so the answer is its full length.
Example 2
nums = [1,2]k = 4return = -1Even the whole array sums to less than four. No subarray reaches the target, so none exists.
Constraints
0 <= nums.length <= 10^5.-10^9 <= nums[i], k <= 10^9.- Sums of consecutive elements can be too large for an
int, but they always fit in a signed 64-bit integer.
More Apple Onsite Interview questions
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- FIFO Mutex Operation TraceONSITE INTERVIEW · Seen Oct 2026
- Implement Hit CounterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Parse Nested HTML into a TreeONSITE INTERVIEW · Seen Oct 2026
- Thread-Safe Concurrent Linked ListONSITE INTERVIEW · Seen Sep 2026
- Palindrome Match PercentageONSITE INTERVIEW · Seen Sep 2026
- Binary Tree Nodes at Distance KONSITE INTERVIEW · Seen Aug 2026
- BST to Sorted Circular Doubly Linked ListONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Shortest Subarray with Sum at Least KOracle · ONSITE INTERVIEWOracle interview questions
- Minimum Size Subarray Sum With NegativesTekion · ONSITE INTERVIEWTekion interview questions
- Shortest Subarray with Sum at Least KGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- Shortest Subarray with Sum at Least KGoogle · PHONE SCREENGoogle interview questions
- Profit AnalysisVirtu Financial · OAVirtu Financial interview questions
- Sliding Window MaximumAmazon · ONSITE INTERVIEW
- Sliding Window MaximumPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Sliding Window MaximumBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Number of Submatrices That Sum to TargetWhatNot · ONSITE INTERVIEWWhatNot interview questions
- Subarray Sum Equals KServiceNow · ONSITE INTERVIEWServiceNow interview questions