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.