Minimum Size Subarray Sum: Leetcode 209 Explanation and Solution

janac
2 min readSep 29, 2020

Problem

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 a minimal length under the problem constraint.

Proof of speed from Leetcode.

Solution

In order to come up with the strategy behind this solution, you must first understand that you will need to use the Sliding Window Algorithm. If you are not completely confident with what that algorithm is, and how to identify when a problem will require the sliding window — please read this article first.

Here’s the code for Leetcode 209:

The strategy is as follows:

  1. Maintain pointers for the beginning and end of your window
  2. Maintain a value which represent the minimum size of your window so…

--

--

janac

Most of my writing is about software. I enjoy summarizing and analyzing books and self-help videos. I am senior software consultant at LazerTechnologies.com.