Be the first user to complete this post

  • 0
Add to List
Medium

89. Find Smallest Subarray Exceeding a Target Sum

Objective: Given an array and a number n, find the smallest subarray whose sum is greater than the given integer.

Examples:

Input[] = { 1, 5, 20, 70, 8}
Integer = 97
Output : Min Length = 3 Subarray = [20, 70, 8]

Input[] = { 1, 10, 3, 40, 18}
Integer = 50
Output : Min Length = 2 Subarray = [40, 18]

Approach:

Naive Approach: Use 2 loops. Time Complexity - O(n2).

Better Approach: Time Complexity - O(n)

  • Initialize minLength = length of the array and say the given number is x.
  • Take variables currSum = 0, start = 0
  • Do the linear scan in an array and start adding each element to the currSum.
  • If currSum > x then start subtracting elements from the start.(currSum-arrA[start]) check the length of the subarray, If it is less than the minLength (currentIndex-start<minLength) update minLength and store the current index and start index for finding the subarray.
  • See the code below for a better understanding
 

Output:

Min length of subarray to get 50 is : 2
SubArray is:   40   18