Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

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