medium Minimum Size Subarray Sum
Problem Statement
Given a nums array containing positive integers and a positive integer target, return the minimum length of a
subarray having the sum of elements greater than or equal to target. If there is no such subarray, return 0 instead.
Examples
Example 1:
- Input:
target = 15,nums = [1, 2, 3, 4, 5, 6, 7, 8] - Expected Output:
2 - Justification: The subarray
[7, 8]has a sum of15, which is equal totargetand is the smallest possible subarray.
Example 2:
- Input:
target = 11,nums = [2, 1, 5, 2, 8] - Expected Output:
3 - Justification: The subarray
[5, 2, 8]has a sum of15, which meets thetargetand is the smallest possible subarray.
Example 3:
- Input:
target = 8,nums = [2, 1, 5, 2, 3] - Expected Output:
3 - Justification: The subarray
[5, 2, 3]has a sum of10, which meets thetargetand is the smallest possible subarray.
Constraints:
- 1 <= target <= 109
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 104
Pattern cue: variable window — smallest length with sum ≥ target. Requires positive elements so expand/shrink is monotonic; if negatives appear, this template fails.
Try it yourself
Try solving this question here:
🎯 STRICT STANDOUT: Why / worked+complexity / pattern+when-not / edge / drills — Minimum Size Subarray Sum medium
Why this concept exists (judgment layer)
Smallest length with sum ≥ target under POSITIVE integers is the classic shrinkable variable window: positivity makes sum monotone in L and R so greedy shrink is optimal. Negatives break the pattern — panel checks that precondition.
Worked example with complexity derivation
target=15, nums=[1,2,3,4,5,6,7,8]:
Expand until sum≥15; shrink while still ≥15 tracking min len.
… eventually window [7,8] sum=15 length 2 optimal.
target=11, [2,1,5,2,8]: [5,2,8] sum=15 len=3 (minimal).
Each pointer ≤n moves → Θ(n) time Θ(1) space.
Brute all i..j: Θ(n²) sums; n=1e5 timeout.
If a single nums[i]≥target → answer 1.
Pattern + when-NOT / named alternative
PATTERN: variable window minimize length under sum≥target; requires nums[i]>0. WHEN NOT: negatives/zeros allowed → cannot shrink greedily; use prefix+binary search O(n log n) or other methods. Maximize length under budget → inverse window (Ones III). Unsorted pair equal target → two pointers/hash not subarray.
Edge case / failure mode
Edges: no subarray reaches target → 0; whole array sum < target → 0; large single element. Failure: applying template when negatives present (sum not monotone).
Hostile-panel drills (defend the decision)
Q1. Why positivity is required.
Model answer: If negatives exist, shrinking left might increase sum — greedy invalidation fails.
Q2. Trace min length for target=8, [2,1,5,2,3].
Model answer: [5,2,3]=10 len 3; [2,3] after shrink paths — min is 3 as justified.
Q3. Complexity under n=1e5.
Model answer: O(n) two pointers clears; O(n²) does not.
✅ Solution Minimum Size Subarray Sum
Problem Statement
Given a nums array containing positive integers and a positive integer target, return the minimum length of a
subarray having the sum of elements greater than or equal to target. If there is no such subarray, return 0 instead.
Examples
Example 1:
- Input:
target = 15,nums = [1, 2, 3, 4, 5, 6, 7, 8] - Expected Output:
2 - Justification: The subarray
[7, 8]has a sum of15, which is equal totargetand is the smallest possible subarray.
Example 2:
- Input:
target = 11,nums = [2, 1, 5, 2, 8] - Expected Output:
3 - Justification: The subarray
[5, 2, 8]has a sum of15, which meets thetargetand is the smallest possible subarray.
Example 3:
- Input:
target = 8,nums = [2, 1, 5, 2, 3] - Expected Output:
3 - Justification: The subarray
[5, 2, 3]has a sum of10, which meets thetargetand is the smallest possible subarray.
Constraints:
- 1 <= target <= 109
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 104
Pattern
Variable window — smallest window whose sum ≥ target (positive integers only). Recognition: minimize length subject to an aggregate threshold; elements are positive, so growing the window never decreases the sum and shrinking never increases it (monotonicity). Template: expand end, adding; while sum ≥ target, record length and shrink start. Both pointers advance at most n times → O(n).
When-not: if the array can contain negatives, this shrink logic is wrong (expanding can lower the sum). Switch to prefix sums + binary search on bounds (O(n log n)) or a different technique. Fixed-size "sum of every window of size k" uses the fixed template, not this one.
Edge: no subarray reaches target → return 0. Single element ≥ target → return 1. Empty array is outside constraints here.
Solution
Expand a right pointer while accumulating the window sum. Whenever the sum is at least target, record the window length and shrink from the left as far as the sum stays ≥ target, seeking the shortest valid window. Positivity of the inputs is what makes "shrink while valid" safe and optimal.
Each index is added and removed at most once, so total work is linear.
Step-by-Step Algorithm
-
Initialize Variables:
- Set
startto0to denote the start of the sliding window. - Set
min_lengthto a large number (e.g., infinity) to keep track of the minimum subarray length found. - Set
current_sumto0to keep track of the sum of the current window.
- Set
-
Iterate Through Array:
- Use a
forloop withendranging from0ton-1(wherenis the length ofnums).
- Use a
-
Expand the Window:
- For each
endindex, addnums[end]tocurrent_sum.
- For each
-
Contract the Window:
- Use a
whileloop to check ifcurrent_sumis greater than or equal totarget. - If it is, update
min_lengthto the smaller ofmin_lengthand the length of the current window (end - start + 1). - Subtract
nums[start]fromcurrent_sumto reduce the window size. - Move the
startpointer to the right by incrementingstart.
- Use a
-
Finalize Result:
- After the loop, check if
min_lengthis still a large number. - If it is, return
0(meaning no valid subarray was found). - Otherwise, return
min_length.
- After the loop, check if
Algorithm Walkthrough
Using Example 1:
Input: target = 15, nums = [1, 2, 3, 4, 5, 6, 7, 8]
-
Initialize Variables:
start = 0min_length = infinitycurrent_sum = 0
-
Iterate Through Array:
-
end = 0: Addnums[0]tocurrent_sum→current_sum = 1current_sum(1) is less thantarget(15), so do nothing.
-
end = 1: Addnums[1]tocurrent_sum→current_sum = 3current_sum(3) is less thantarget(15), so do nothing.
-
end = 2: Addnums[2]tocurrent_sum→current_sum = 6current_sum(6) is less thantarget(15), so do nothing.
-
end = 3: Addnums[3]tocurrent_sum→current_sum = 10current_sum(10) is less thantarget(15), so do nothing.
-
end = 4: Addnums[4]tocurrent_sum→current_sum = 15current_sum(15) is equal totarget(15), so:- Update
min_length→min_length = min(infinity, 4 - 0 + 1) = 5 - Subtract
nums[start](1) fromcurrent_sum→current_sum = 14 - Increment
start→start = 1
- Update
-
end = 5: Addnums[5]tocurrent_sum→current_sum = 20current_sum(20) is greater thantarget(15), so:- Update
min_length→min_length = min(5, 5 - 1 + 1) = 5 - Subtract
nums[start](2) fromcurrent_sum→current_sum = 18 - Increment
start→start = 2
- Update
current_sum(18) is still greater thantarget(15), so:- Update
min_length→min_length = min(5, 5 - 2 + 1) = 4 - Subtract
nums[start](3) fromcurrent_sum→current_sum = 15 - Increment
start→start = 3
- Update
current_sum(15) is equal totarget(15), so:- Update
min_length→min_length = min(4, 5 - 3 + 1) = 3 - Subtract
nums[start](4) fromcurrent_sum→current_sum = 11 - Increment
start→start = 4
- Update
-
end = 6: Addnums[6]tocurrent_sum→current_sum = 18current_sum(18) is greater thantarget(15), so:- Update
min_length→min_length = min(3, 6 - 4 + 1) = 3 - Subtract
nums[start](5) fromcurrent_sum→current_sum = 13 - Increment
start→start = 5
- Update
-
end = 7: Addnums[7]tocurrent_sum→current_sum = 21current_sum(21) is greater thantarget(15), so:- Update
min_length→min_length = min(3, 7 - 5 + 1) = 3 - Subtract
nums[start](6) fromcurrent_sum→current_sum = 15 - Increment
start→start = 6
- Update
current_sum(15) is equal totarget(15), so:- Update
min_length→min_length = min(3, 7 - 6 + 1) = 2 - Subtract
nums[start](7) fromcurrent_sum→current_sum = 8 - Increment
start→start = 7
- Update
-
-
Finalize Result:
min_lengthis 2, which is not infinity.- Return
min_length, which is2.
This is the smallest subarray whose sum is at least 15, and it is [7, 8].
Code
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int minLength = Integer.MAX_VALUE; // Initialize minLength to a large number
int currentSum = 0; // To keep track of the current sum
int start = 0; // Starting index of the sliding window
for (int end = 0; end < n; end++) {
currentSum += nums[end]; // Add the current element to currentSum
while (currentSum >= target) { // While the current sum is greater than or equal to target
minLength = Math.min(minLength, end - start + 1); // Update minLength
currentSum -= nums[start]; // Remove the starting element from currentSum
start++; // Move the starting index to the right
}
}
return minLength == Integer.MAX_VALUE ? 0 : minLength; // Return 0 if no subarray was found
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] nums2 = { 2, 1, 5, 2, 8 };
int[] nums3 = { 2, 1, 5, 2, 3 };
System.out.println(sol.minSubArrayLen(15, nums1)); // Output: 2
System.out.println(sol.minSubArrayLen(11, nums2)); // Output: 3
System.out.println(sol.minSubArrayLen(8, nums3)); // Output: 3
}
}
Complexity Analysis
- Time Complexity: The time complexity of this algorithm is
, where n is the length of the array. This is because each element is processed at most twice, once by the endpointer and once by thestartpointer. - Space Complexity: The space complexity of this algorithm is
because we are using a constant amount of extra space regardless of the input size.
🎯 STRICT STANDOUT — Minimum Size Subarray Sum
1. Why / judgment
Minimize length subject to sum ≥ target. With positive nums, sum is monotonic in window growth: expand end; while valid, record length and shrink start. Negatives break monotonicity — switch prefix+binary search.
2. Trace recompute + complexity (K11)
target=15, nums=[1,2,3,4,5,6,7,8]
Expand to end=4 sum=15 → minLen=5; shrink while sum≥15
Continue as page walkthrough; end=7 brings 8 in; shrink to [7,8] → minLen=2 ✓
Pointer accounting: end moves n times; start moves ≤n times; body O(1)
→ total operations ≤ 2n → Θ(n) time, Θ(1) space
If negatives allowed: this while-shrink can miss optima → wrong algorithm.
Prefix sums + binary search lower_bound: Θ(n log n) time, Θ(n) space (prefix).
n=1e5 forbids Θ(n²) double loop.
3. Pattern — VARIABLE WINDOW MIN LENGTH (THRESHOLD SUM) (K12)
Name: Expand/shrink min window sum ≥ target (positives).
Recognition: shortest subarray meeting additive threshold; positive integers.
When-NOT: negatives present → prefix+BS or other; fixed k sum → fixed window; count distinct ≤k → map window.
4. Edge hand-run (K13)
target=100, nums=[1,2,3] → never → 0
target=7, nums=[8] → 1
target=15, [1,2,3,4,5,6,7,8] → 2
target=11, [2,1,5,2,8] → [5,2,8] len 3 ✓
5. Interviewer follow-ups
Q1. Prove O(n).
A: start and end each advance at most n; amortized O(1) per advance.
Q2. Why positives required?
A: Shrinking must never increase sum; expanding must never decrease sum — fails with negatives.
Q3. Return if none?
A: 0 (minLength left at sentinel).
Recognize it: Best/longest/count over a contiguous subarray or substring → grow the window, shrink it when a constraint breaks.
▶ Visualize this problem (step it, predict each fork)
🤖 Don't fully get this? Learn it with Claude
Stuck on Minimum Size Subarray Sum? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Minimum Size Subarray Sum** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Minimum Size Subarray Sum** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Minimum Size Subarray Sum**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Minimum Size Subarray Sum**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.