Skip to content

Commit 0a5ce05

Browse files
Add 'Minimum Size Subarray Sum'
1 parent b9b4f30 commit 0a5ce05

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ A collection of LeetCode solutions
5454

5555
[Middle of the Linked List](./src/middle_of_the_linked_list.py)
5656

57+
[Minimum Size Subarray Sum](./src/minimum_size_subarray_sum.py)
58+
5759
[Product of Array Except Self](./src/product_of_array_except_self.py)
5860

5961
[Remove Nth Node From End of List](./src/remove_nth_node_from_end_of_list.py)

src/minimum_size_subarray_sum.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
209. Minimum Size Subarray Sum
3+
4+
https://leetcode.com/problems/minimum-size-subarray-sum
5+
6+
NOTES
7+
* Use a sliding window.
8+
9+
A subarray is a contiguous, non-empty sequence of elements within an array.
10+
Here, we just apply the canonical subarray/substring solution using a sliding
11+
window.
12+
"""
13+
14+
import sys
15+
16+
17+
class Solution:
18+
def minSubArrayLen(self, target: int, nums: list[int]) -> int:
19+
left, right, current_sum, current_size, minimum_size = 0, 0, 0, 0, sys.maxsize
20+
21+
while right < len(nums):
22+
current_sum += nums[right]
23+
current_size += 1
24+
while left <= right and current_sum >= target:
25+
if current_size < minimum_size:
26+
minimum_size = current_size
27+
current_sum -= nums[left]
28+
current_size -= 1
29+
left += 1
30+
right += 1
31+
32+
return minimum_size if minimum_size < sys.maxsize else 0
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
209. Minimum Size Subarray Sum
3+
4+
https://leetcode.com/problems/minimum-size-subarray-sum
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.minimum_size_subarray_sum import Solution
10+
11+
12+
class TestSolution(TestCase):
13+
def test_1(self):
14+
exp = 2
15+
assert Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]) == exp
16+
17+
def test_2(self):
18+
exp = 1
19+
assert Solution().minSubArrayLen(4, [1, 4, 4]) == exp
20+
21+
def test_3(self):
22+
exp = 0
23+
assert Solution().minSubArrayLen(11, [1, 1, 1, 1, 1, 1, 1, 1]) == exp

0 commit comments

Comments
 (0)