Prepin
Log in

Locate the subarray of specified size k that has the smallest sum.

Approach / Explanation

This question prompts you to create a function or method that identifies a contiguous subarray of size "k" with the least sum within a specified array or list of integers. Essentially, you are required to traverse the array using a sliding window of size k and monitor the minimum sum of the elements within each window. Key aspects to consider when answering this question include: Familiarity with the sliding window algorithm. Basic understanding of array operations such as summation and comparison. Knowledge of various data structures like arrays or lists. To tackle this problem efficiently, you can employ the sliding window technique by maintaining a window of size 'k'. For each window, calculate the sum of its elements. After obtaining the sum for the current window, shift the window to the right by one element. Repeat this process until you reach the end of the array, all the while keeping track of the minimum sum encountered.

Suggested Answer

Let's consider an array = [10, 3, 2, 5, 7, 3], with a subarray size of k = 3. To determine the minimum sum of a subarray of size k, we start by computing the sum of the first window (subarray) of size k, which is 10 + 3 + 2 = 15. Next, we move our window one position forward. The new window is {3, 2, 5}. We calculate the sum of this new window: 3 + 2 + 5 = 10, which is less than 15. Therefore, this becomes our new minimum sum. We continue this process for the next window. The next set is {2, 5, 7}, and its sum is 2 + 5 + 7 = 14, which is greater than 10. Thus, we stop here. Finally, the window shifts to {5, 7, 3}, and its sum is 5 + 7 + 3 = 15, which exceeds our current minimum sum of 10. After examining all the windows, we conclude that the minimum sum of any window (subarray) of size 'k' is 10.

Alternative Answer

Consider the array = [5, 12, -1, -5, 3, -3, 2], with a subarray size of k = 4. We will once again utilize the sliding window technique. The sum of the first window is calculated as 5 + 12 - 1 - 5 = 11. Moving to the next window {12, -1, -5, 3}, the sum is 12 - 1 - 5 + 3 = 9, which is lower than 11. Therefore, this becomes our new minimum sum. The subsequent window is {-1, -5, 3, -3}, and its sum is -1 - 5 + 3 - 3 = -6. This is even smaller! Thus, it is now our new minimum sum. We will keep repeating this process until we reach the last window. Consequently, the minimum sum of a subarray of size 'k' in this array is -6.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.