Open In App

Smallest subarray with sum greater than a given value

Last Updated : 26 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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. 

C++
// C++ program to find smallest
// subarray with sum greater than x
#include <bits/stdc++.h>
using namespace std;

// Returns length of smallest subarray
// with sum greater than x. If no such
// subarray exists, returns 0.
int smallestSubWithSum(int x, vector<int> &arr) {
    int n = arr.size();
    int res = INT_MAX;

    // Pick every element as starting point
    for (int i = 0; i < n; i++) {
        int curr = 0;

        for (int j = i; j < n; j++) {
            curr += arr[j];

            if (curr > x) {
                res = min(res, j - i + 1);
                break;
            }
        }
    }

    // Return 0 if answer does
    // not exists.
    if (res == INT_MAX)
        return 0;

    return res;
}

int main() {
    vector<int> arr = {1, 4, 45, 6, 10, 19};
    int x = 51;

    cout << smallestSubWithSum(x, arr);

    return 0;
}
Java Python C# Javascript

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.
C++
// C++ program to find smallest
// subarray with sum greater than x
#include <bits/stdc++.h>
using namespace std;

// Returns the length of the smallest subarray
// with sum greater than or equal to x
int smallestSubWithSum(int x, vector<int> &arr) {
    int n = arr.size();

    int res = INT_MAX;
    vector<int> preSum(n + 1, 0);

    // Compute the prefix sums
    for (int i = 1; i <= n; i++)
        preSum[i] = preSum[i - 1] + arr[i - 1];

    // Iterate through each starting index
    for (int i = 1; i <= n; i++) {

        // Target sum for current subarray
        int toFind = x + preSum[i - 1];

        // Find the first prefix sum > target
        auto bound = lower_bound(preSum.begin(), preSum.end(), toFind);

        if (bound != preSum.end() && *bound != toFind) {
            int len = bound - (preSum.begin() + i - 1);
            res = min(res, len);
        }
    }

    // If subarray does not exists
    if (res == INT_MAX)
        return 0;

    return res;
}

int main() {
  
    vector<int> arr = {1, 4, 45, 6, 10, 19};
    int x = 51;

    cout << smallestSubWithSum(x, arr);

    return 0;
}
Java Python C# JavaScript

Output
3

[Expected Approach] – Using Two Pointers – O(n) Time and O(1) Space

The idea is to use two pointer approach 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.

C++
// C++ program to find smallest 
// subarray with sum greater than x
#include <bits/stdc++.h>
using namespace std;

// Returns the length of the smallest subarray 
// with sum greater than or equal to x
int smallestSubWithSum(int x, vector<int>& arr) {

    int i = 0, j = 0;
    int sum = 0;
    int ans = INT_MAX;
    
    while (j < arr.size()) {
        
        // Expand window until sum > x 
        // or end of array reached
        while (j < arr.size() && sum <= x) {
            sum += arr[j++];
        }
        
        // If we reached end of array and sum 
        // still <= x, no valid subarray exists
        if (j == arr.size() && sum <= x) break;
        
        // Minimize window from start 
        // while maintaining sum > x
        while (i < j && sum - arr[i] > x) {
            sum -= arr[i++];
        }
        
        ans = min(ans, j-i);
        
        // Remove current start 
        // element and shift window
        sum -= arr[i];
        i++;
    }
    
    // Return 0 if no valid subarray
    // found, else return min length
    if (ans == INT_MAX) return 0;
    return ans;
}

int main() {
    vector<int> arr = {1, 4, 45, 6, 10, 19};
    int x = 51;

    cout<<smallestSubWithSum(x, arr);

    return 0;
}
Java Python C# Javascript

Output
3

Why is the time complexity O(n)? If you take a closer look, you can notice that every item goes inside the window at most once and goes out of the window at most once. Adding and removing an item takes O(1) time. So we overall do at-most 2n work. Hence the time complexity is O(n).

How to handle negative numbers? The above solution may not work if input array contains negative numbers. For example arr[] = {- 8, 1, 4, 2, -6}. To handle negative numbers, add a condition to ignore subarrays with negative sums. We can use the solution discussed in Find subarray with given sum with negatives allowed in constant space.



Next Article

Similar Reads

three90RightbarBannerImg