Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fb9bd0f

Browse files
committed
Add Minimum Size Subarray Sum
1 parent 4adddcf commit fb9bd0f

File tree

2 files changed

+118
-0
lines changed

2 files changed

+118
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Minimum Size Subarray Sum
2+
3+
## Problem Description
4+
5+
Given an array of positive integers nums and a positive integer target, return the
6+
minimal length of a subarray whose sum is greater than or equal to `target`.
7+
If there is no such subarray, return `0` instead.
8+
9+
**Example 1:**
10+
11+
Input: `target = 7`, nums = `[2,3,1,2,4,3]`
12+
Output: `2`
13+
Explanation: The subarray `[4,3]` has the minimal length under the problem constraint.
14+
15+
**Example 2:**
16+
17+
Input: `target = 4`, `nums = [1,4,4]`
18+
Output: `1`
19+
20+
**Example 3:**
21+
22+
Input: `target = 11`, `nums = [1,1,1,1,1,1,1,1]`
23+
Output: `0`
24+
25+
Constraints:
26+
27+
* `1 <= target <= 109`
28+
* `1 <= nums.length <= 105`
29+
* `1 <= nums[i] <= 104`
30+
31+
32+
## Solution
33+
34+
```python
35+
def min_sub_array_len(target: int, nums: list[int]) -> int:
36+
"""
37+
Finds the minimal length of a contiguous subarray of which the sum is greater than or equal to the target.
38+
If there is no such subarray, returns 0.
39+
40+
:param target: The target sum to achieve.
41+
:param nums: List of integers representing the array.
42+
:return: The minimal length of the subarray, or 0 if no such subarray exists.
43+
"""
44+
first_pointer = 0
45+
current_sum = 0
46+
min_len = float('inf')
47+
48+
for second_pointer in range(len(nums)):
49+
current_sum += nums[second_pointer]
50+
51+
while current_sum >= target:
52+
min_len = min(min_len, second_pointer - first_pointer + 1)
53+
current_sum -= nums[first_pointer]
54+
first_pointer += 1
55+
56+
return min_len if min_len != float('inf') else 0
57+
```
58+
59+
* **Time Complexity:** $O(n)$
60+
* **Space Complexity:** $O(1)$
61+
62+
## Explanation of the Solution
63+
64+
The algorithm efficiently tracks a "window" of elements in the array using two pointers
65+
(`first_pointer` and `second_pointer`). The window expands and contracts dynamically to
66+
find the smallest valid subarray.
67+
68+
1. Initialization
69+
* `first_pointer = 0` (marks the start of the current window)
70+
* `current_sum = 0` (stores the sum of elements in the current window)
71+
* `min_len = ∞` (tracks the smallest valid window length found so far)
72+
2. Expand the Window (Move second_pointer)
73+
* Iterate through nums using second_pointer (from `0` to `len(nums)-1`).
74+
* Add `nums[second_pointer]` to `current_sum`.
75+
3. Check if the Window Sum ≥ Target
76+
* If `current_sum >= target`, it means the current window (`[first_pointer ... second_pointer]`) is a valid subarray.
77+
* Update `min_len` to the smaller of:
78+
* Current `min_len`
79+
* Length of the current window (`second_pointer - first_pointer + 1`)
80+
4. Contract the Window (Move `first_pointer`)
81+
* While `current_sum >= target`:
82+
* Remove `nums[first_pointer]` from `current_sum` (shrinking the window from the left).
83+
* Move `first_pointer` forward.
84+
* This ensures we find the smallest possible valid window ending at `second_pointer``.
85+
5. Repeat Until the End of the Array
86+
* Continue expanding (`second_pointer++`) and contracting (`first_pointer++`) until all possible windows are checked.
87+
6. Return the Result
88+
* If a valid subarray was found (`min_len` is not ∞), return `min_len`.
89+
* Otherwise, return `0`.
90+
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def min_sub_array_len(target: int, nums: list[int]) -> int:
2+
"""
3+
Finds the minimal length of a contiguous subarray of which the sum is greater than or equal to the target.
4+
If there is no such subarray, returns 0.
5+
6+
:param target: The target sum to achieve.
7+
:param nums: List of integers representing the array.
8+
:return: The minimal length of the subarray, or 0 if no such subarray exists.
9+
"""
10+
first_pointer = 0
11+
current_sum = 0
12+
min_len = float('inf')
13+
14+
for second_pointer in range(len(nums)):
15+
current_sum += nums[second_pointer]
16+
17+
while current_sum >= target:
18+
min_len = min(min_len, second_pointer - first_pointer + 1)
19+
current_sum -= nums[first_pointer]
20+
first_pointer += 1
21+
22+
return min_len if min_len != float('inf') else 0
23+
24+
assert min_sub_array_len(target=7, nums=[2,3,1,2,4,3]) == 2, 'Test 1 Failed'
25+
assert min_sub_array_len(target=4, nums=[1,4,4]) == 1, 'Test 2 Failed'
26+
assert min_sub_array_len(target=11, nums=[1,1,1,1,1,1,1,1]) == 0, 'Test 3 Failed'
27+
assert min_sub_array_len(target=11, nums=[1,2,3,4,5]) == 3, 'Test 4 Failed'
28+
assert min_sub_array_len(target=15, nums=[1,2,3,4,5]) == 5, 'Test 5 Failed'

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /