educative.io

Smallest Subarray With a Greater Sum

The JS solution does not give the correct solution when the given array is [84,-37,32,40,95]
167, the output should be 3 but it returns 5. Please look into this


Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/4578892830474240

Hi @Varun_Chillara!
Thank you for pointing out this issue. The solution provided in the lesson lacked the specific instruction of the input being positive, otherwise, it will not work. This was explained in the previous lesson “Sliding Window”, from which this problem is derived, where the restriction for a positive number was stated at the start.
Kindly check for inputs >= 0 and we will add the required non-negative disclaimer asap.
Hope this helps and feel free to ask any other questions if needed.

Hi there,
I think there is an issue with the approach. You are updating Min Length in advance, are you not?


What do you think about it ?

func smallestSubarrayWithGreaterSum(data []float64, sum float64) float64 {
	var windowStart int = 0
	var windowSum float64 = 0
	var minLength float64 = math.MaxFloat64

	for windowEnd := 0; windowEnd < len(data); windowEnd++ {
		windowSum += data[windowEnd]

		if windowSum > sum {
			windowSum -= data[windowStart]
			windowStart++
		}

		if windowSum == sum {
			minLength = math.Min(minLength, float64(windowEnd-windowStart+1))
		}
	}

	if minLength == math.MaxFloat64 {
		return 0
	}

	return minLength
}

Hi @Mark_Humeniuk
There is no issue with our given approach.
Let’s take few examples:

  • We have an input array: [2, 1, 5, 2, 3, 2], S=7
    The length of the smallest subarray with a sum greater than or equal to ‘7’ is 2 because we have a [5, 2] as a subarray of length 2.
  • We have another input array: [3, 4, 1, 1, 6], S=8
    The length of the smallest subarray with a sum greater than or equal to ‘8’ is 3 because we have two possible subarrays [3, 4, 1] or [1, 1, 6] of length 3.
  • We have another input array: [2, 1, 5, 2, 8], S=7
    The length of the smallest subarray with a sum greater than or equal to ‘7’ is 1 because we have one possible subarray [8] of length 1.

You can verify all the above-mentioned examples in the code as follows:

Secondly, there exist many approaches for solving any problem. Our given approach is just for implementation purposes. If you want to use any other approach which seems easier to you, then you can use it.

Hope it will help, Thank you :blush:

1 Like

Hi Muntha
I got it, many thanks

1 Like