Minimum Size Subarray Sum — LeetCode 209 Python Solution

MediumArrayBinary SearchPrefix SumSliding Window
Problem
#209
Reading time
2 min

The problem

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Example

Input
target = 7, nums = [2,3,1,2,4,3]
Output
2
Explanation
The subarray [4,3] has the minimal length under the problem constraint.

Python solution

Python
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        n = len(nums)
        s = list(accumulate(nums, initial=0))
        ans = n + 1
        for i, x in enumerate(s):
            j = bisect_left(s, x + target)
            if j <= n:
                ans = min(ans, j - i)
        return ans if ans <= n else 0

Complexity

MeasureComplexity
Time<code>O(n log(n))</code>
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 209. Minimum Size Subarray Sum is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 209. Minimum Size Subarray Sum?
LeetCode 209. Minimum Size Subarray Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 209. Minimum Size Subarray Sum?
The Python solution on this page runs in <code>O(n log(n))</code>.
What is the space complexity of LeetCode 209. Minimum Size Subarray Sum?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 209. Minimum Size Subarray Sum cover?
LeetCode 209. Minimum Size Subarray Sum is tagged Array, Binary Search, Prefix Sum and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview