Given an integer array, find the minimum sum subarray of size k, where k is a positive integer.

For example,

Input:  {10, 4, 2, 5, 6, 3, 8, 1}, k = 3
 
Output: Minimum sum subarray of size 3 is (1, 3)

Practice this problem

The problem differs from the problem of finding the minimum sum subsequence of size k. Unlike subsequences, subarrays are required to occupy consecutive positions within the original array.

 
We can solve this problem by using the sliding window technique. The idea is to maintain a window of size k. For every array element, include it in the window and remove the window’s leftmost element if the window size is more than k. Also maintain the sum of elements in the current window. If the sum of the current window is less than the minimum found so far, update the minimum sum to the current window sum and store the window’s endpoints.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The minimum sum subarray is (1, 3)

Java


Download  Run Code

Output:

The minimum sum subarray is (1, 3)

Python


Download  Run Code

Output:

The minimum sum subarray is (1, 3)

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
Exercise: Find the minimum product subarray of a given size k