Skip to content

Commit 9db4e72

Browse files
committed
Minimum size subarray sum
1 parent e66912e commit 9db4e72

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 209. Minimum size subarray sum
2+
# Topics: 'Sliding Window', 'Prefix Sum', 'Binary Search', 'Array'
3+
# Level: 'Medium'
4+
5+
# Given an array of positive integers nums and a positive integer target, return the minimal length of a
6+
7+
# whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
8+
9+
10+
11+
# Example 1:
12+
13+
# Input: target = 7, nums = [2,3,1,2,4,3]
14+
# Output: 2
15+
# Explanation: The subarray [4,3] has the minimal length under the problem constraint.
16+
17+
# Example 2:
18+
19+
# Input: target = 4, nums = [1,4,4]
20+
# Output: 1
21+
22+
# Example 3:
23+
24+
# Input: target = 11, nums = [1,1,1,1,1,1,1,1]
25+
# Output: 0
26+
27+
28+
29+
# Constraints:
30+
31+
# 1 <= target <= 109
32+
# 1 <= nums.length <= 105
33+
# 1 <= nums[i] <= 104
34+
35+
from typing import List
36+
37+
class Solution:
38+
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
39+
L = 0
40+
min_len = float('inf')
41+
window = 0
42+
for R in range (len(nums)):
43+
window += nums[R]
44+
45+
while window>=target:
46+
min_len = min(min_len, R-L+1)
47+
window -= nums[L]
48+
L+=1
49+
50+
if min_len == float('inf'):
51+
return 0
52+
53+
return min_len
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import unittest
2+
from typing import List
3+
4+
from min import Solution
5+
6+
# Assuming your Solution class is already defined above
7+
class TestMinSubArrayLen(unittest.TestCase):
8+
9+
def setUp(self):
10+
self.solution = Solution()
11+
12+
def test_example1(self):
13+
self.assertEqual(self.solution.minSubArrayLen(7, [2,3,1,2,4,3]), 2)
14+
15+
def test_example2(self):
16+
self.assertEqual(self.solution.minSubArrayLen(4, [1,4,4]), 1)
17+
18+
def test_example3(self):
19+
self.assertEqual(self.solution.minSubArrayLen(11, [1,1,1,1,1,1,1,1]), 0)
20+
21+
def test_single_element_reach(self):
22+
self.assertEqual(self.solution.minSubArrayLen(5, [5]), 1)
23+
24+
def test_single_element_not_reach(self):
25+
self.assertEqual(self.solution.minSubArrayLen(10, [5]), 0)
26+
27+
def test_entire_array_needed(self):
28+
self.assertEqual(self.solution.minSubArrayLen(15, [1,2,3,4,5]), 5)
29+
30+
if __name__ == '__main__':
31+
unittest.main()

0 commit comments

Comments
 (0)