Notes

Personal notes on various topics

View on GitHub

Intuition

To find the minimal length of a contiguous subarray with sum at least target, we can use a sliding window. By expanding and shrinking the window, we efficiently track the sum and update the minimal length when the sum meets or exceeds the target.

Approach

Complexity

Code

from typing import List

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        l, r, s = 0, 0, 0
        res = float("inf")

        for r in range(len(nums)):
            s += nums[r]

            while s >= target:
                res = min(res, r - l + 1)
                s -= nums[l]
                l += 1

        return int(0 if res > len(nums) else res)

Back to Problem Statement