Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1 Output: 1
Example 2:
Input: nums = [1,2], k = 4 Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3 Output: 3
Constraints:
1 <= nums.length <= 105-105 <= nums[i] <= 1051 <= k <= 109Problem summary: Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Sliding Window · Monotonic Queue
[1] 1
[1,2] 4
[2,-1,2] 3
shortest-subarray-with-or-at-least-k-ii)shortest-subarray-with-or-at-least-k-i)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #862: Shortest Subarray with Sum at Least K
class Solution {
public int shortestSubarray(int[] nums, int k) {
int n = nums.length;
long[] s = new long[n + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = s[i] + nums[i];
}
Deque<Integer> q = new ArrayDeque<>();
int ans = n + 1;
for (int i = 0; i <= n; ++i) {
while (!q.isEmpty() && s[i] - s[q.peek()] >= k) {
ans = Math.min(ans, i - q.poll());
}
while (!q.isEmpty() && s[q.peekLast()] >= s[i]) {
q.pollLast();
}
q.offer(i);
}
return ans > n ? -1 : ans;
}
}
// Accepted solution for LeetCode #862: Shortest Subarray with Sum at Least K
func shortestSubarray(nums []int, k int) int {
n := len(nums)
s := make([]int, n+1)
for i, x := range nums {
s[i+1] = s[i] + x
}
q := []int{}
ans := n + 1
for i, v := range s {
for len(q) > 0 && v-s[q[0]] >= k {
ans = min(ans, i-q[0])
q = q[1:]
}
for len(q) > 0 && s[q[len(q)-1]] >= v {
q = q[:len(q)-1]
}
q = append(q, i)
}
if ans > n {
return -1
}
return ans
}
# Accepted solution for LeetCode #862: Shortest Subarray with Sum at Least K
class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
s = list(accumulate(nums, initial=0))
q = deque()
ans = inf
for i, v in enumerate(s):
while q and v - s[q[0]] >= k:
ans = min(ans, i - q.popleft())
while q and s[q[-1]] >= v:
q.pop()
q.append(i)
return -1 if ans == inf else ans
// Accepted solution for LeetCode #862: Shortest Subarray with Sum at Least K
struct Solution;
use std::collections::VecDeque;
impl Solution {
fn shortest_subarray(a: Vec<i32>, k: i32) -> i32 {
let n = a.len();
let mut queue: VecDeque<usize> = VecDeque::new();
let mut prefix = vec![0; n + 1];
queue.push_back(0);
let mut res = std::usize::MAX;
for i in 0..n {
prefix[i + 1] = prefix[i] + a[i];
while let Some(&j) = queue.front() {
if prefix[i + 1] - prefix[j] >= k {
res = res.min(i + 1 - j);
queue.pop_front();
} else {
break;
}
}
while let Some(&j) = queue.back() {
if prefix[i + 1] <= prefix[j] {
queue.pop_back();
} else {
break;
}
}
queue.push_back(i + 1);
}
if res == std::usize::MAX {
-1
} else {
res as i32
}
}
}
#[test]
fn test() {
let a = vec![1];
let k = 1;
let res = 1;
assert_eq!(Solution::shortest_subarray(a, k), res);
let a = vec![1, 2];
let k = 4;
let res = -1;
assert_eq!(Solution::shortest_subarray(a, k), res);
let a = vec![2, -1, 2];
let k = 3;
let res = 3;
assert_eq!(Solution::shortest_subarray(a, k), res);
}
// Accepted solution for LeetCode #862: Shortest Subarray with Sum at Least K
function shortestSubarray(nums: number[], k: number): number {
const [n, MAX] = [nums.length, Number.POSITIVE_INFINITY];
const s = Array(n + 1).fill(0);
const q: number[] = [];
let ans = MAX;
for (let i = 0; i < n; i++) {
s[i + 1] = s[i] + nums[i];
}
for (let i = 0; i < n + 1; i++) {
while (q.length && s[i] - s[q[0]] >= k) {
ans = Math.min(ans, i - q.shift()!);
}
while (q.length && s[i] <= s[q.at(-1)!]) {
q.pop();
}
q.push(i);
}
return ans === MAX ? -1 : ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.