Smallest Subarray with sum greater than a given value
Pattern: Sliding window: variable size
Grow the window until its sum passes x, then shrink from the left while it still passes, recording the length each time. Non-negative values make this safe.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given an array of whole numbers that are zero or more, and a number x. Return the length of the shortest block
of neighbouring elements whose sum is strictly greater than x, or 0 if no block is. For example, [1, 4, 45, 6, 0, 19]
with x = 51 gives 3 (4 + 45 + 6 = 55), and [1, 2, 4] with x = 8 gives 0.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
smallestSubWithSum and the rule "return 0 when there is no such block" are this guide's own.
Think first
- If a block's sum is already above
x, does adding more elements help you find a shorter answer? - Once the window passes
x, how short can you make it while keeping it abovex? - Why does this need the values to be zero or more?
Hints
Brute force, and why it fails
From each start, add elements until the sum passes x: O(n²) in the worst case. The window is O(n).
The key insight
With non-negative values, a longer window never has a smaller sum. So once a window passes x, only shorter windows from
the left side are worth trying, and both edges move forwards only.
Dry run
| sum | 50 |
|---|---|
| best | none |
arr = [1, 4, 45, 6, 0, 19] and x = 51. Grow the window. After 1, 4 and 45 the sum is 50, not above 51.
The plan
best = n + 1, sum = 0, left = 0
for right from 0 to n - 1:
sum = sum + arr[right]
while sum > x:
best = min(best, right - left + 1)
sum = sum - arr[left]
left = left + 1
return 0 if best == n + 1 else best
Complexity
- Time
O(n)- Space
O(1)
Each edge moves at most n times. Only a sum and two indexes are stored.
Edge cases
- One element already above
x: 1. - The whole array does not pass
x: 0. - Zeros, as in
[0, 0, 3]withx = 2: 1. Zeros never help, and the window drops them.
I've built my logic, show the code
Java
class Solution {
public int smallestSubWithSum(int[] arr, int x) {
int n = arr.length;
int best = n + 1; // n + 1 means "no window found yet"
long sum = 0;
int left = 0;
for (int right = 0; right < n; right++) {
sum += arr[right];
while (sum > x) { // the window works: record it, then try a shorter one
best = Math.min(best, right - left + 1);
sum -= arr[left];
left++;
}
}
return best == n + 1 ? 0 : best;
}
}C++
class Solution {
public:
int smallestSubWithSum(vector<int>& arr, int x) {
int n = static_cast<int>(arr.size());
int best = n + 1; // n + 1 means "no window found yet"
long long sum = 0;
int left = 0;
for (int right = 0; right < n; right++) {
sum += arr[right];
while (sum > x) { // the window works: record it, then try a shorter one
best = min(best, right - left + 1);
sum -= arr[left];
left++;
}
}
return best == n + 1 ? 0 : best;
}
};Python
class Solution:
def smallestSubWithSum(self, arr: list[int], x: int) -> int:
n = len(arr)
best = n + 1 # n + 1 means "no window found yet"
total = left = 0
for right, v in enumerate(arr):
total += v
while total > x: # the window works: record it, then try a shorter one
best = min(best, right - left + 1)
total -= arr[left]
left += 1
return 0 if best == n + 1 else bestCommon mistakes
- Using
≥instead of>, which finds blocks equal tox. - Recording the length after shrinking past the point where the sum drops to
xor below. - Using this window with negative values. Then a longer window can have a smaller sum, and the method breaks.