Minimum Size Subarray Sum
LeetCode 209 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Positive numbers ⇒ expand then shrink.
আমি Minimum Size Subarray Sum (LeetCode 209) এভাবে সমাধান করেছি — Variable Window – Shortest / Minimum প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
All numbers are positive, so extending a window only increases its sum and shrinking only decreases it. Expand right until the sum reaches the target, then shrink from the left while it still does, recording the shortest length.
Approach
- 1
Add nums[r] to the sum.
- 2
While sum ≥ target: record r − l + 1, subtract nums[l], l++.
- 3
Return 0 if nothing qualified.
আমি কীভাবে সমাধান করেছি
Sliding windowPythonO(n) time · O(1) space
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
l=0
r=0
sum=0
min_length = float("inf")
while r<len(nums):
sum+=nums[r]
while sum>=target:
min_length = min(min_length,r-l+1)
sum-=nums[l]
l+=1
r+=1
return 0 if min_length==float("inf") else min_lengthMinimum Size Subarray Sum — সাধারণ প্রশ্ন
Minimum Size Subarray Sum-এর পেছনে intuition কী?
All numbers are positive, so extending a window only increases its sum and shrinking only decreases it. Expand right until the sum reaches the target, then shrink from the left while it still does, recording the shortest length.
Minimum Size Subarray Sum (LeetCode 209) কীভাবে সমাধান করবেন?
1. Add nums[r] to the sum. 2. While sum ≥ target: record r − l + 1, subtract nums[l], l++. 3. Return 0 if nothing qualified.
Minimum Size Subarray Sum-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Sliding window।)
Minimum Size Subarray Sum-এ সাধারণ ভুলগুলো কী?
Sliding window relies on positivity — with negatives use prefix sums.