Find the Shortest Contiguous Segment Reaching a Sum Threshold
Quick Overview
Find the Shortest Contiguous Segment Reaching a Sum Threshold. Return the minimum length of a nonempty contiguous segment of nums whose sum is at least k.
Find the Shortest Contiguous Segment Reaching a Sum Threshold
Company: DevRev
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
### Problem
Return the minimum length of a nonempty contiguous segment of `nums` whose sum is at least `k`. Return `-1` if no segment qualifies. Values may be negative, so extending a segment need not increase its sum.
```cpp
class Solution {
public:
int shortestSubarray(vector<int>& nums, int k);
};
```
### Examples
**Example 1:**
```text
Input: nums = [2,-1,2,3], k = 4
Output: 2
Explanation: The last two values sum to 5. No single value reaches 4.
```
**Example 2:**
```text
Input: nums = [1,-2,1], k = 2
Output: -1
Explanation: Every segment has sum at most 1.
```
### Constraints
- `1 <= nums.length <= 10^5`
- `-10^5 <= nums[i] <= 10^5`
- `1 <= k <= 10^9`
### Contract considerations
The result is a length, not the segment. Equality with k qualifies. The answer may be -1 even when the total array length is large.
```hint Read the boundary condition
Compare two starting prefixes: when does the later start dominate the earlier one?
```
### Boundary reminders
The result is a length, not the segment. Equality with k qualifies. The answer may be -1 even when the total array length is large.
Overview: Find the Shortest Contiguous Segment Reaching a Sum Threshold. Return the minimum length of a nonempty contiguous segment of nums whose sum is at least k.
Find the Shortest Contiguous Segment Reaching a Sum Threshold
DevRev
Sep 3, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0
Problem
Return the minimum length of a nonempty contiguous segment of nums whose sum is at least k. Return -1 if no segment qualifies. Values may be negative, so extending a segment need not increase its sum.
class Solution {
public:
int shortestSubarray(vector<int>& nums, int k);
};
Examples
Example 1:
Input: nums = [2,-1,2,3], k = 4
Output: 2
Explanation: The last two values sum to 5. No single value reaches 4.
Example 2:
Input: nums = [1,-2,1], k = 2
Output: -1
Explanation: Every segment has sum at most 1.
Constraints
1 <= nums.length <= 10^5
-10^5 <= nums[i] <= 10^5
1 <= k <= 10^9
Contract considerations
The result is a length, not the segment. Equality with k qualifies. The answer may be -1 even when the total array length is large.
Boundary reminders
The result is a length, not the segment. Equality with k qualifies. The answer may be -1 even when the total array length is large.