VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-length-subarray-sum-greater-given-value/

⇱ Smallest subarray with sum greater than a given value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest subarray with sum greater than a given value

Last Updated : 30 Mar, 2026

Given an array arr[] of integers and a number x, the task is to find the smallest subarray with a sum strictly greater than x.

Examples:

Input: x = 51, arr[] = [1, 4, 45, 6, 0, 19]
Output: 3
Explanation: Minimum length subarray is [4, 45, 6]

Input: x = 100, arr[] = [1, 10, 5, 2, 7]
Output: 0
Explanation: No subarray exist

[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space

The idea is to use two nested loops. The outer loop picks a starting element, the inner loop considers all elements (on right side of current start) as ending element. Whenever sum of elements between current start and end becomes greater than x, update the result if current length is smaller than the smallest length so far. 


Output
3

[Better Approach] - Prefix Sum and Binary Search - O(n Log n) Time and O(n) Space

The idea is to store the prefix sum in an array and then for every index i, perform binary search in the range [i+1, n] to find the minimum index such that preSum[j] > preSum[i] + x.

Below is the step by step of above approach:

  • Compute prefix sum in an array preSum[].
  • Iterate through preSum[] and find lower bound for x + preSum[i], here lower bound means index of first value greater than x + preSum[i].
  • If the lower bound is found and it's not equal to x i.e., the subarray sum is greater than the x, calculate the length of current subarray and update result if the current result is a smaller value.

Output
3

[Expected Approach] - Using Sliding Window - O(n) Time and O(1) Space

The idea is to maintain a sliding window, where we keep expanding the window by adding elements until the sum becomes greater than x, then we try to minimize this window by shrinking it from the start while maintaining the sum > x condition. This way, we explore all possible subarrays and keep track of the smallest valid length.


Output
3
Comment