Minimum Size Subarray Sum
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find the shortest continuous sub-list whose sum is at least target (all numbers are positive).
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Expand right until the sum reaches the target. Then what?
- Hint 2Shrink from the left while the sum is still enough, noting the length each time.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
You save coins every day and want the shortest run of consecutive days whose savings reach ₹7. Keep adding days on the right until you reach ₹7 or more. Now you can afford to drop the oldest days on the left: keep dropping while you are still at ₹7 or more, noting how short the run became. Then add more days on the right and repeat.
- The obvious way
Try all start/end pairs: O(n²).
- The key insight
All numbers are positive, so once the window total reaches the target you can try to make it shorter from the left; removing numbers can only lower the total. Both edges only move forward, so every number enters and leaves once: O(n).
- The algorithm
- Window total = 0, left edge at the start, best = infinity.
- Add the next number on the right to the total.
- While the total is at least the target: note the window length, drop the left number and move the left edge on.
- At the end return best (0 if no window ever reached the target).
Watch it run
Exampletarget = 7, savings = [2, 3, 1, 2, 4, 3]
Add days until the total reaches 7: 2 + 3 + 1 + 2 = 8, run length 4.
best 4
Where people slip
- This window needs non-negative numbers; with negatives use prefix sums and a deque.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def min_sub_array_len(target, nums):
left = 0
total = 0
best = float("inf")
for right, number in enumerate(nums):
total += number
while total >= target: # enough: try a shorter run
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.