DEV Community

codingpineapple
codingpineapple

Posted on

1

209. Minimum Size Subarray Sum

Alt Text

Question:

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

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

Solution:

Time complexity: O(n)
Space complexity: O(1)

var minSubArrayLen = function(s, nums) {
    let windowSum = 0
    let output = Infinity;
    let windowStart = 0;
    for (let windowEnd = 0; windowEnd < nums.length; windowEnd++) {
      windowSum += nums[windowEnd];
      // shrink the window until the windowSum is smaller than s
      while (windowSum >= s) {
        output = Math.min(output, windowEnd - windowStart + 1);
        // subtract the element at the windowStart index
        windowSum -= nums[windowStart];
        // change windowStart to the next element
        windowStart++; 
      }
    }
    return output == Infinity ? 0 : output;
};

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of Stellar post

Discover what it takes to launch a Web3 startup

Bringing your Web3 idea to life and launching a startup can be a difficult, complicated process. Check out the Stellar Dev Diaries to learn from a team that is makiung it happen, in real time!

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay