# Smallest Subarray with a given Sum

## Problem

Given an array of positive numbers and a positive number ‘S,’ find the length of the **smallest contiguous subarray whose sum is greater than or equal to ‘S’**. Return 0 if no such subarray exists.

{% hint style="info" %}
For example:

```
Input: [2, 1, 5, 2, 3, 2], S=7 
Output: 2
Explanation: The smallest subarray with a sum
great than or equal to '7' is [5, 2].
```

```
Input: [2, 1, 5, 2, 8], S=7 
Output: 1
Explanation: The smallest subarray with a sum
greater than or equal to '7' is [8].
```

```
Input: [3, 4, 1, 1, 6], S=8 
Output: 3
Explanation: Smallest subarrays with a sum 
greater than or equal to '8' are [3, 4, 1] 
or [1, 1, 6].
```

{% endhint %}

### Thought Process

* We will use a dynamic window (adjust size as we go depending on condition)

* The condition that will determine our window size is if the total sum is greater than the *s*, if this is true then we will continually shrink our window till the total sum is less than *s*.

## Solution

```
def smallest_subarray_with_given_sum(s, nums):
        minWindow = float("inf")
        totalSum = 0
        start = 0
        
        
        for i in range(len(nums)):
            totalSum+=nums[i]
            while totalSum >= s:
                minWindow = min(minWindow, i+1-start)
                totalSum-=nums[start]
                start+=1
        if minWindow == float("inf"):
            return 0
        return minWindow


```

## Key Points

* Using a dynamic window

* When the total sum of a contigous subarray is greater than *s* is when we start to shrink our window

## Time Complexity

* **Time:** $$O(N)$$ because the outer `for` loop runs for all elements, and the inner `while` loop processes each element only once; therefore, the time complexity of the algorithm will be $$O(N+N)$$ , which is asymptotically equivalent to $$O(N)$$.

* **Space:** O(1)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/sliding-window/smallest-subarray-with-a-given-sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
