The Wayback Machine - https://web.archive.org/web/20240818163938/https://www.geeksforgeeks.org/minimum-length-subarray-sum-greater-given-value/
Open In App

Smallest subarray with sum greater than a given value

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
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 greater than the given value. 

Examples:

arr[] = {1, 4, 45, 6, 0, 19}
x = 51
Output: 3
Minimum length subarray is {4, 45, 6}
arr[] = {1, 10, 5, 2, 7}
x = 9
Output: 1
Minimum length subarray is {10}
arr[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}
x = 280
Output: 4
Minimum length subarray is {100, 1, 0, 200}
arr[] = {1, 2, 4}
x = 8
Output : Not Possible
Whole array sum is smaller than 8.

Naive approach: A simple solution 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 more than the given number, update the result if current length is smaller than the smallest length so far. 

Below is the implementation of the above approach:

C++




# include <iostream>
using namespace std;
  
// Returns length of smallest subarray with sum greater than x.
// If there is no subarray with given sum, then returns n+1
int smallestSubWithSum(int arr[], int n, int x)
{
    //  Initialize length of smallest subarray as n+1
     int min_len = n + 1;
  
     // Pick every element as starting point
     for (int start=0; start<n; start++)
     {
          // Initialize sum starting with current start
          int curr_sum = arr[start];
  
          // If first element itself is greater
          if (curr_sum > x) return 1;
  
          // Try different ending points for current start
          for (int end=start+1; end<n; end++)
          {
              // add last element to current sum
              curr_sum += arr[end];
  
              // If sum becomes more than x and length of
              // this subarray is smaller than current smallest
              // length, update the smallest length (or result)
              if (curr_sum > x && (end - start + 1) < min_len)
                 min_len = (end - start + 1);
          }
     }
     return min_len;
}
  
/* Driver program to test above function */
int main()
{
    int arr1[] = {1, 4, 45, 6, 10, 19};
    int x = 51;
    int n1 = sizeof(arr1)/sizeof(arr1[0]);
    int res1 = smallestSubWithSum(arr1, n1, x);
    (res1 == n1+1)? cout << "Not possible\n" :
                    cout << res1 << endl;
  
    int arr2[] = {1, 10, 5, 2, 7};
    int n2 = sizeof(arr2)/sizeof(arr2[0]);
    x  = 9;
    int res2 = smallestSubWithSum(arr2, n2, x);
    (res2 == n2+1)? cout << "Not possible\n" :
                    cout << res2 << endl;
  
    int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250};
    int n3 = sizeof(arr3)/sizeof(arr3[0]);
    x  = 280;
    int res3 = smallestSubWithSum(arr3, n3, x);
    (res3 == n3+1)? cout << "Not possible\n" :
                    cout << res3 << endl;
  
    return 0;
}


Java




import java.io.*;
class SmallestSubArraySum
{
    // Returns length of smallest subarray with sum greater than x.
    // If there is no subarray with given sum, then returns n+1
    static int smallestSubWithSum(int arr[], int n, int x)
    {
        //  Initialize length of smallest subarray as n+1
        int min_len = n + 1;
  
        // Pick every element as starting point
        for (int start = 0; start < n; start++)
        {
            // Initialize sum starting with current start
            int curr_sum = arr[start];
  
            // If first element itself is greater
            if (curr_sum > x)
                return 1;
  
            // Try different ending points for current start
            for (int end = start + 1; end < n; end++)
            {
                // add last element to current sum
                curr_sum += arr[end];
  
                // If sum becomes more than x and length of
                // this subarray is smaller than current smallest
                // length, update the smallest length (or result)
                if (curr_sum > x && (end - start + 1) < min_len)
                    min_len = (end - start + 1);
            }
        }
        return min_len;
    }
  
    // Driver program to test above functions
    public static void main(String[] args)
    {
        int arr1[] = {1, 4, 45, 6, 10, 19};
        int x = 51;
        int n1 = arr1.length;
        int res1 = smallestSubWithSum(arr1, n1, x);
        if (res1 == n1+1)
           System.out.println("Not Possible");
        else
           System.out.println(res1);
  
  
        int arr2[] = {1, 10, 5, 2, 7};
        int n2 = arr2.length;
        x = 9;
        int res2 = smallestSubWithSum(arr2, n2, x);
        if (res2 == n2+1)
           System.out.println("Not Possible");
        else
           System.out.println(res2);
  
        int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250};
        int n3 = arr3.length;
        x = 280;
        int res3 = smallestSubWithSum(arr3, n3, x);
        if (res3 == n3+1)
           System.out.println("Not Possible");
        else
           System.out.println(res3);
    }
}
  
// This code has been contributed by Mayank Jaiswal


Python3




# Python3 program to find Smallest 
# subarray with sum greater 
# than a given value
  
# Returns length of smallest subarray
# with sum greater than x. If there
# is no subarray with given sum, 
# then returns n+1
def smallestSubWithSum(arr, n, x):
  
    # Initialize length of smallest
    # subarray as n+1
    min_len = n + 1
  
    # Pick every element as starting point
    for start in range(0,n):
      
        # Initialize sum starting 
        # with current start
        curr_sum = arr[start]
  
        # If first element itself is greater
        if (curr_sum > x):
            return 1
  
        # Try different ending points
        # for current start
        for end in range(start+1,n):
          
            # add last element to current sum
            curr_sum += arr[end]
  
            # If sum becomes more than x 
            # and length of this subarray
            # is smaller than current smallest
            # length, update the smallest 
            # length (or result)
            if curr_sum > x and (end - start + 1) < min_len:
                min_len = (end - start + 1)
          
    return min_len;
  
  
# Driver program to test above function */
arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x);
if res1 == n1+1:
    print("Not possible")
else:
    print(res1)
  
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x);
if res2 == n2+1:
    print("Not possible")
else:
    print(res2)
  
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
if res3 == n3+1:
    print("Not possible") 
else:
    print(res3)
      
# This code is contributed by Smitha Dinesh Semwal


C#




// C# program to find Smallest 
// subarray with sum greater 
// than a given value
using System;
  
class GFG
{
      
    // Returns length of smallest
    // subarray with sum greater 
    // than x. If there is no 
    // subarray with given sum,
    // then returns n+1
    static int smallestSubWithSum(int []arr, 
                                  int n, int x)
    {
        // Initialize length of 
        // smallest subarray as n+1
        int min_len = n + 1;
  
        // Pick every element
        // as starting point
        for (int start = 0; start < n; start++)
        {
            // Initialize sum starting
            // with current start
            int curr_sum = arr[start];
  
            // If first element
            // itself is greater
            if (curr_sum > x)
                return 1;
  
            // Try different ending 
            // points for current start
            for (int end = start + 1; 
                     end < n; end++)
            {
                // add last element
                // to current sum
                curr_sum += arr[end];
  
                // If sum becomes more than
                // x and length of this 
                // subarray is smaller than
                // current smallest length,
                // update the smallest 
                // length (or result)
                if (curr_sum > x && 
                        (end - start + 1) < min_len)
                    min_len = (end - start + 1);
            }
        }
        return min_len;
    }
  
    // Driver Code
    static public void Main ()
    {
        int []arr1 = {1, 4, 45, 
                      6, 10, 19};
        int x = 51;
        int n1 = arr1.Length;
        int res1 = smallestSubWithSum(arr1, 
                                      n1, x);
        if (res1 == n1 + 1)
        Console.WriteLine("Not Possible");
        else
        Console.WriteLine(res1);
  
  
        int []arr2 = {1, 10, 5, 2, 7};
        int n2 = arr2.Length;
        x = 9;
        int res2 = smallestSubWithSum(arr2, 
                                      n2, x);
        if (res2 == n2 + 1)
        Console.WriteLine("Not Possible");
        else
        Console.WriteLine(res2);
  
        int []arr3 = {1, 11, 100, 1, 0, 
                      200, 3, 2, 1, 250};
        int n3 = arr3.Length;
        x = 280;
        int res3 = smallestSubWithSum(arr3, 
                                      n3, x);
        if (res3 == n3 + 1)
        Console.WriteLine("Not Possible");
        else
        Console.WriteLine(res3);
    }
}
  
// This code is contributed by ajit


Javascript




<script>
  
// Returns length of smallest subarray with sum greater than x.
// If there is no subarray with given sum, then returns n+1
function smallestSubWithSum(arr, n, x)
{
  
    // Initialize length of smallest subarray as n+1
    let min_len = n + 1;
  
    // Pick every element as starting point
    for (let start=0; start<n; start++)
    {
      
        // Initialize sum starting with current start
        let curr_sum = arr[start];
  
        // If first element itself is greater
        if (curr_sum > x) return 1;
  
        // Try different ending points for current start
        for (let end=start+1; end<n; end++)
        {
          
            // add last element to current sum
            curr_sum += arr[end];
  
            // If sum becomes more than x and length of
            // this subarray is smaller than current smallest
            // length, update the smallest length (or result)
            if (curr_sum > x && (end - start + 1) < min_len)
                min_len = (end - start + 1);
        }
    }
    return min_len;
}
  
/* Driver program to test above function */
    let arr1 = [1, 4, 45, 6, 10, 19];
    let x = 51;
    let n1 = arr1.length;
    let res1 = smallestSubWithSum(arr1, n1, x);
    (res1 == n1 + 1)? document.write("Not possible<br>") :
                    document.write(res1 + "<br>");
  
    let arr2 = [1, 10, 5, 2, 7];
    let n2 = arr2.length;
    x = 9;
    let res2 = smallestSubWithSum(arr2, n2, x);
    (res2 == n2 + 1)? document.write("Not possible<br>") :
                    document.write(res2 + "<br>");
  
    let arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250];
    let n3 = arr3.length;
    x = 280;
    let res3 = smallestSubWithSum(arr3, n3, x);
    (res3 == n3 + 1)? document.write("Not possible<br>") :
                    document.write(res3 + "<br>");
  
// This code is contributed by Surbhi Tyagi.
</script>


PHP




<?php
// Returns length of smallest 
// subarray with sum greater 
// than x. If there is no 
// subarray with given sum, 
// then returns n+1
function smallestSubWithSum($arr, $n, $x)
{
    // Initialize length of 
    // smallest subarray as n+1
    $min_len = $n + 1;
  
    // Pick every element 
    // as starting point
    for ($start = 0; $start < $n; $start++)
    {
        // Initialize sum starting
        // with current start
        $curr_sum = $arr[$start];
  
        // If first element 
        // itself is greater
        if ($curr_sum > $x) return 1;
  
        // Try different ending 
        // points for current start
        for ($end= $start + 1; $end < $n; $end++)
        {
            // add last element
            // to current sum
            $curr_sum += $arr[$end];
  
            // If sum becomes more than 
            // x and length of this subarray 
            // is smaller than current 
            // smallest length, update the 
            // smallest length (or result)
            if ($curr_sum > $x && 
                   ($end - $start + 1) < $min_len)
                $min_len = ($end - $start + 1);
        }
    }
    return $min_len;
}
  
// Driver Code
$arr1 = array (1, 4, 45, 
               6, 10, 19);
$x = 51;
$n1 = sizeof($arr1);
$res1 = smallestSubWithSum($arr1, $n1, $x);
  
if (($res1 == $n1 + 1) == true)
    echo "Not possible\n" ;
else
    echo $res1 , "\n";
  
$arr2 = array(1, 10, 5, 2, 7);
$n2 = sizeof($arr2);
$x = 9;
$res2 = smallestSubWithSum($arr2, $n2, $x);
  
if (($res2 == $n2 + 1) == true) 
    echo "Not possible\n" ;
else
    echo $res2 , "\n";
  
$arr3 = array (1, 11, 100, 1, 0,
               200, 3, 2, 1, 250);
$n3 = sizeof($arr3);
$x = 280;
$res3 = smallestSubWithSum($arr3, $n3, $x);
if (($res3 == $n3 + 1) == true)
    echo "Not possible\n" ;
else
    echo $res3 , "\n";
  
// This code is contributed by ajit
?>


Output

3
1
4










Time Complexity: O(n2).
Auxiliary Space: O(1)

Efficient Solution: This problem can be solved in O(n) time using the idea used in this post.

C++14




// O(n) solution for finding smallest subarray with sum
// greater than x
#include <iostream>
using namespace std;
  
// Returns length of smallest subarray with sum greater than
// x. If there is no subarray with given sum, then returns
// n+1
int smallestSubWithSum(int arr[], int n, int x)
{
    // Initialize current sum and minimum length
    int curr_sum = 0, min_len = n + 1;
  
    // Initialize starting and ending indexes
    int start = 0, end = 0;
    while (end < n) {
        // Keep adding array elements while current sum
        // is smaller than or equal to x
        while (curr_sum <= x && end < n)
            curr_sum += arr[end++];
  
        // If current sum becomes greater than x.
        while (curr_sum > x && start < n) {
            // Update minimum length if needed
            if (end - start < min_len)
                min_len = end - start;
  
            // remove starting elements
            curr_sum -= arr[start++];
        }
    }
    return min_len;
}
  
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 4, 45, 6, 10, 19 };
    int x = 51;
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int res1 = smallestSubWithSum(arr1, n1, x);
    (res1 == n1 + 1) ? cout << "Not possible\n"
                     : cout << res1 << endl;
  
    int arr2[] = { 1, 10, 5, 2, 7 };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    x = 9;
    int res2 = smallestSubWithSum(arr2, n2, x);
    (res2 == n2 + 1) ? cout << "Not possible\n"
                     : cout << res2 << endl;
  
    int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 };
    int n3 = sizeof(arr3) / sizeof(arr3[0]);
    x = 280;
    int res3 = smallestSubWithSum(arr3, n3, x);
    (res3 == n3 + 1) ? cout << "Not possible\n"
                     : cout << res3 << endl;
  
    return 0;
}


Java




// O(n) solution for finding smallest subarray with sum
// greater than x
import java.io.*;
class SmallestSubArraySum {
    // Returns length of smallest subarray with sum greater
    // than x. If there is no subarray with given sum, then
    // returns n+1
    static int smallestSubWithSum(int arr[], int n, int x)
    {
        // Initialize current sum and minimum length
        int curr_sum = 0, min_len = n + 1;
  
        // Initialize starting and ending indexes
        int start = 0, end = 0;
        while (end < n) {
            // Keep adding array elements while current sum
            // is smaller than or equal to x
            while (curr_sum <= x && end < n)
                curr_sum += arr[end++];
  
            // If current sum becomes greater than x.
            while (curr_sum > x && start < n) {
                // Update minimum length if needed
                if (end - start < min_len)
                    min_len = end - start;
  
                // remove starting elements
                curr_sum -= arr[start++];
            }
        }
        return min_len;
    }
    // Driver program to test above functions
    public static void main(String[] args)
    {
        int arr1[] = { 1, 4, 45, 6, 10, 19 };
        int x = 51;
        int n1 = arr1.length;
        int res1 = smallestSubWithSum(arr1, n1, x);
        if (res1 == n1 + 1)
            System.out.println("Not Possible");
        else
            System.out.println(res1);
  
        int arr2[] = { 1, 10, 5, 2, 7 };
        int n2 = arr2.length;
        x = 9;
        int res2 = smallestSubWithSum(arr2, n2, x);
        if (res2 == n2 + 1)
            System.out.println("Not Possible");
        else
            System.out.println(res2);
  
        int arr3[]
            = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 };
        int n3 = arr3.length;
        x = 280;
        int res3 = smallestSubWithSum(arr3, n3, x);
        if (res3 == n3 + 1)
            System.out.println("Not Possible");
        else
            System.out.println(res3);
    }
}
  
// This code has been contributed by Mayank Jaiswal


Python3




# O(n) solution for finding smallest
# subarray with sum greater than x
  
# Returns length of smallest subarray
# with sum greater than x. If there
# is no subarray with given sum, then
# returns n + 1
  
  
def smallestSubWithSum(arr, n, x):
  
    # Initialize current sum and minimum length
    curr_sum = 0
    min_len = n + 1
  
    # Initialize starting and ending indexes
    start = 0
    end = 0
    while (end < n):
  
        # Keep adding array elements while current
        # sum is smaller than or equal to x
        while (curr_sum <= x and end < n):
            curr_sum += arr[end]
            end += 1
  
        # If current sum becomes greater than x.
        while (curr_sum > x and start < n):
  
            # Update minimum length if needed
            if (end - start < min_len):
                min_len = end - start
  
            # remove starting elements
            curr_sum -= arr[start]
            start += 1
  
    return min_len
  
  
# Driver program
arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x)
print("Not possible") if (res1 == n1 + 1) else print(res1)
  
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x)
print("Not possible") if (res2 == n2 + 1) else print(res2)
  
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
print("Not possible") if (res3 == n3 + 1) else print(res3)
  
# This code is contributed by
# Smitha Dinesh Semwal


C#




// O(n) solution for finding
// smallest subarray with sum
// greater than x
using System;
  
class GFG {
  
    // Returns length of smallest
    // subarray with sum greater
    // than x. If there is no
    // subarray with given sum,
    // then returns n+1
    static int smallestSubWithSum(int[] arr, int n, int x)
    {
        // Initialize current
        // sum and minimum length
        int curr_sum = 0, min_len = n + 1;
  
        // Initialize starting
        // and ending indexes
        int start = 0, end = 0;
        while (end < n) {
            // Keep adding array elements
            // while current sum is smaller
            // than or equal to x
            while (curr_sum <= x && end < n)
                curr_sum += arr[end++];
  
            // If current sum becomes
            // greater than x.
            while (curr_sum > x && start < n) {
                // Update minimum
                // length if needed
                if (end - start < min_len)
                    min_len = end - start;
  
                // remove starting elements
                curr_sum -= arr[start++];
            }
        }
        return min_len;
    }
  
    // Driver Code
    static public void Main()
    {
        int[] arr1 = { 1, 4, 45, 6, 10, 19 };
        int x = 51;
        int n1 = arr1.Length;
        int res1 = smallestSubWithSum(arr1, n1, x);
        if (res1 == n1 + 1)
            Console.WriteLine("Not Possible");
        else
            Console.WriteLine(res1);
  
        int[] arr2 = { 1, 10, 5, 2, 7 };
        int n2 = arr2.Length;
        x = 9;
        int res2 = smallestSubWithSum(arr2, n2, x);
        if (res2 == n2 + 1)
            Console.WriteLine("Not Possible");
        else
            Console.WriteLine(res2);
  
        int[] arr3
            = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 };
        int n3 = arr3.Length;
        x = 280;
        int res3 = smallestSubWithSum(arr3, n3, x);
        if (res3 == n3 + 1)
            Console.WriteLine("Not Possible");
        else
            Console.WriteLine(res3);
    }
}
  
// This code is contributed by akt_mit


Javascript




<script>
// O(n) solution for finding smallest subarray with sum
// greater than x
  
// Returns length of smallest subarray with sum greater than
// x. If there is no subarray with given sum, then returns
// n+1
function smallestSubWithSum(arr, n, x)
{
    // Initialize current sum and minimum length
    let curr_sum = 0, min_len = n + 1;
  
    // Initialize starting and ending indexes
    let start = 0, end = 0;
    while (end < n) {
        // Keep adding array elements while current sum
        // is smaller than or equal to x
        while (curr_sum <= x && end < n)
            curr_sum += arr[end++];
  
        // If current sum becomes greater than x.
        while (curr_sum > x && start < n) {
            // Update minimum length if needed
            if (end - start < min_len)
                min_len = end - start;
  
            // remove starting elements
            curr_sum -= arr[start++];
        }
    }
    return min_len;
}
  
/* Driver program to test above function */
let arr1 = [ 1, 4, 45, 6, 10, 19 ];
let x = 51;
let n1 = arr1.length;
let res1 = smallestSubWithSum(arr1, n1, x);
(res1 == n1 + 1) ? document.write("Not possible<br>")
    : document.write(res1 + "<br>");
  
let arr2 = [ 1, 10, 5, 2, 7 ];
let n2 = arr2.length;
x = 9;
let res2 = smallestSubWithSum(arr2, n2, x);
(res2 == n2 + 1) ? document.write("Not possible<br>")
    : document.write(res2 + "<br>");
  
let arr3 = [ 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 ];
let n3 = arr3.length;
x = 280;
let res3 = smallestSubWithSum(arr3, n3, x);
(res3 == n3 + 1) ? document.write("Not possible<br>")
    : document.write(res3 + "<br>");
      
    // This code is contributed by subham348.
</script>


PHP




<?php
// O(n) solution for finding 
// smallest subarray with sum 
// greater than x
  
// Returns length of smallest
// subarray with sum greater 
// than x. If there is no 
// subarray with given sum, 
// then returns n+1
function smallestSubWithSum($arr, 
                            $n, $x)
{
    // Initialize current 
    // sum and minimum length
    $curr_sum = 0; 
    $min_len = $n + 1;
  
    // Initialize starting 
    // and ending indexes
    $start = 0;
    $end = 0;
    while ($end < $n)
    {
        // Keep adding array elements 
        // while current sum is smaller
        // than or equal to x
        while ($curr_sum <= $x && 
               $end < $n)
            $curr_sum += $arr[$end++];
  
        // If current sum becomes
        // greater than x.
        while ($curr_sum > $x &&
               $start < $n)
        {
            // Update minimum
            // length if needed
            if ($end - $start < $min_len)
                $min_len = $end - $start;
  
            // remove starting elements
            $curr_sum -= $arr[$start++];
        }
    }
    return $min_len;
}
  
// Driver Code
$arr1 = array(1, 4, 45, 
              6, 10, 19);
$x = 51;
$n1 = sizeof($arr1);
$res1 = smallestSubWithSum($arr1, 
   
                           $n1, $x);
if($res1 == $n1 + 1) 
echo "Not possible\n" ;
else
echo $res1 ,"\n";
  
$arr2 = array(1, 10, 5, 2, 7);
$n2 = sizeof($arr2);
$x = 9;
$res2 = smallestSubWithSum($arr2, 
                           $n2, $x);
if($res2 == $n2 + 1) 
echo "Not possible\n" ;
else
echo $res2,"\n";
  
$arr3 = array(1, 11, 100, 1, 0, 
              200, 3, 2, 1, 250);
$n3 = sizeof($arr3);
$x = 280;
$res3 = smallestSubWithSum($arr3, 
                           $n3, $x);
                             
if($res3 == $n3 + 1)
echo "Not possible\n" ;
else
echo $res3, "\n";
  
// This code is contributed by ajit
?>


Output

3
1
4










Time Complexity: O(n).
Auxiliary Space: O(1)

Another Approach: Binary Search 

  1. First calculates the cumulative sum of the vector elements and stores them in the sums vector.
  2. Then iterates through the sums vector and finds the lower bound of the target sum for each possible subarray.
  3. If the lower bound is found and it’s not equal to the target sum (i.e., the subarray sum is greater than the target),
  4. Calculates the length of the subarray and updates the ans variable if the length is smaller than the current value.
  5. Finally, returns the ans value or 0 if ans was not updated.

C++




// O(n log(n) solution for finding smallest subarray with
// sum greater than x
#include <bits/stdc++.h>
using namespace std;
  
int smallestSubArrayLen(int target, vector<int>& nums)
{
    // Get the length of the input vector
    int n = nums.size();
    // If the vector is empty, return 0
    if (n == 0)
        return 0;
    // Initialize the minimum subarray length to INT_MAX-1
    int ans = INT_MAX - 1;
    // Create a new vector "sums" with size n+1, initialized
    // to all zeros
    vector<int> sums(n + 1, 0);
    // Compute the running sum of nums and store it in
    // "sums"
    for (int i = 1; i <= n; i++)
        sums[i] = sums[i - 1] + nums[i - 1];
    // Iterate through each starting index i
    for (int i = 1; i <= n; i++) {
        // Calculate the target sum for the subarray
        // starting at index i
        int to_find = target + sums[i - 1];
        // Find the first element in "sums" that is >=
        // to_find
        auto bound = lower_bound(sums.begin(), sums.end(),
                                 to_find);
        // If such an element is found and it is not equal
        // to to_find itself
        if (bound != sums.end() && *bound != to_find) {
            // Compute the length of the subarray and update
            // ans if necessary
            int len = bound - (sums.begin() + i - 1);
            ans = min(ans, len);
        }
    }
    // Return ans if it was updated, otherwise return 0
    return (ans != INT_MAX - 1) ? ans : 0;
}
  
/* Driver program to test above function */
int main()
{
    vector<int> arr1 = { 1, 4, 45, 6, 10, 19 };
    int target1 = 51;
    cout << "Length of Smallest Subarray :"
         << smallestSubArrayLen(target1, arr1) << endl;
  
    vector<int> arr2 = { 1, 10, 5, 2, 7 };
    int target2 = 9;
    cout << "Length of Smallest Subarray :"
         << smallestSubArrayLen(target2, arr2) << endl;
  
    vector<int> arr3 = { 1, 1, 1, 1, 1, 1, 1, 1 };
    int target3 = 11;
    cout << "Length of Smallest Subarray :"
         << smallestSubArrayLen(target3, arr3) << endl;
  
    vector<int> arr4
        = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 };
    int target4 = 280;
    cout << "Length of Smallest Subarray :"
         << smallestSubArrayLen(target4, arr4) << endl;
  
    return 0;
}


Java




import java.util.Arrays;
  
public class GFG {
    public static int smallestSubArrayLen(int target, int[] nums) {
        // Get the length of the input array
        int n = nums.length;
        // If the array is empty, return 0
        if (n == 0) {
            return 0;
        }
        // Initialize the minimum subarray length to a large value
        int ans = Integer.MAX_VALUE;
        // Create a new array "sums" with size n+1, initialized to all zeros
        int[] sums = new int[n + 1];
        // Compute the running sum of nums and store it in "sums"
        for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
        // Iterate through each starting index i
        for (int i = 1; i <= n; i++) {
            // Calculate the target sum for the subarray starting at index i
            int toFind = target + sums[i - 1];
            // Find the first element in "sums" that is >= toFind
            int bound = Arrays.binarySearch(sums, toFind);
            if (bound < 0) {
                bound = -bound - 1;
            }
            // If such an element is found and it is not equal to toFind itself
            if (bound != sums.length && sums[bound] != toFind) {
                // Compute the length of the subarray and update ans if necessary
                int length = bound - (i - 1);
                ans = Math.min(ans, length);
            }
        }
        // Return ans if it was updated, otherwise return 0
        return (ans != Integer.MAX_VALUE) ? ans : 0;
    }
  
    public static void main(String[] args) {
        int[] arr1 = {1, 4, 45, 6, 10, 19};
        int target1 = 51;
        System.out.println("Length of Smallest Subarray: " + smallestSubArrayLen(target1, arr1));
  
        int[] arr2 = {1, 10, 5, 2, 7};
        int target2 = 9;
        System.out.println("Length of Smallest Subarray: " + smallestSubArrayLen(target2, arr2));
  
        int[] arr3 = {1, 1, 1, 1, 1, 1, 1, 1};
        int target3 = 11;
        System.out.println("Length of Smallest Subarray: " + smallestSubArrayLen(target3, arr3));
  
        int[] arr4 = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250};
        int target4 = 280;
        System.out.println("Length of Smallest Subarray: " + smallestSubArrayLen(target4, arr4));
    }
}


Python3




# O(n log(n) solution for finding smallest subarray with
# sum greater than 
from bisect import bisect_left
# Function to find the smallest subarray length with a 
# sum greater than a target value
def smallestSubArrayLen(target, nums):
    # Get the length of the input list
    n = len(nums)
    # If the list is empty, return 0
    if n == 0:
        return 0
    # Initialize the minimum subarray length to a large value
    ans = float('inf')
    # Create a new list "sums" with size n+1, initialized to all zeros
    sums = [0] * (n + 1)
    # Compute the running sum of nums and store it in "sums"
    for i in range(1, n + 1):
        sums[i] = sums[i - 1] + nums[i - 1]
    # Iterate through each starting index i
    for i in range(1, n + 1):
        # Calculate the target sum for the subarray starting at index i
        to_find = target + sums[i - 1]
        # Find the first element in "sums" that is >= to_find
        bound = bisect_left(sums, to_find)
        # If such an element is found and it is not equal to to_find itself
        if bound != len(sums) and sums[bound] != to_find:
            # Compute the length of the subarray and update ans if necessary
            length = bound - (i - 1)
            ans = min(ans, length)
    # Return ans if it was updated, otherwise return 0
    return ans if ans != float('inf') else 0
  
# Driver code to test the function
arr1 = [1, 4, 45, 6, 10, 19]
target1 = 51
print("Length of Smallest Subarray:", smallestSubArrayLen(target1, arr1))
  
arr2 = [1, 10, 5, 2, 7]
target2 = 9
print("Length of Smallest Subarray:", smallestSubArrayLen(target2, arr2))
  
arr3 = [1, 1, 1, 1, 1, 1, 1, 1]
target3 = 11
print("Length of Smallest Subarray:", smallestSubArrayLen(target3, arr3))
  
arr4 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
target4 = 280
print("Length of Smallest Subarray:", smallestSubArrayLen(target4, arr4))


C#




// Nikunj Sonigara
  
using System;
using System.Collections.Generic;
  
class Program
{
    // Function to find the length of the smallest subarray whose sum is greater than or equal to the target.
    static int SmallestSubArrayLen(int target, List<int> nums)
    {
        int n = nums.Count;
        if (n == 0)
            return 0;
  
        int ans = int.MaxValue - 1;
        List<int> sums = new List<int>(n + 1);
  
        sums.Add(0);
  
        // Calculate the cumulative sum of the elements in the 'nums' list.
        for (int i = 1; i <= n; i++)
            sums.Add(sums[i - 1] + nums[i - 1]);
  
        for (int i = 1; i <= n; i++)
        {
            int toFind = target + sums[i - 1];
  
            // Use binary search to find the index in 'sums' where 'toFind' would be located.
            int bound = BinarySearch(sums, toFind);
  
            if (bound != sums.Count && sums[bound] != toFind)
            {
                // Calculate the length of the subarray and update the 'ans' if it's smaller.
                int len = bound - (i - 1);
                ans = Math.Min(ans, len);
            }
        }
  
        // If no subarray was found, return 0. Otherwise, return the minimum length found.
        return (ans != int.MaxValue - 1) ? ans : 0;
    }
  
    // Binary search to find the index of the target sum in the 'sums' list.
    static int BinarySearch(List<int> sums, int target)
    {
        int left = 0;
        int right = sums.Count - 1;
  
        while (left <= right)
        {
            int mid = left + (right - left) / 2;
  
            if (sums[mid] == target)
                return mid;
            else if (sums[mid] < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
  
        return left;
    }
  
    static void Main()
    {
        List<int> arr1 = new List<int> { 1, 4, 45, 6, 10, 19 };
        int target1 = 51;
        Console.WriteLine("Length of Smallest Subarray: " + SmallestSubArrayLen(target1, arr1));
  
        List<int> arr2 = new List<int> { 1, 10, 5, 2, 7 };
        int target2 = 9;
        Console.WriteLine("Length of Smallest Subarray: " + SmallestSubArrayLen(target2, arr2));
  
        List<int> arr3 = new List<int> { 1, 1, 1, 1, 1, 1, 1, 1 };
        int target3 = 11;
        Console.WriteLine("Length of Smallest Subarray: " + SmallestSubArrayLen(target3, arr3));
  
        List<int> arr4 = new List<int> { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 };
        int target4 = 280;
        Console.WriteLine("Length of Smallest Subarray: " + SmallestSubArrayLen(target4, arr4));
    }
}


Javascript




// O(n log(n) solution for finding smallest subarray with
// sum greater than x
  
// Function to find the smallest subarray length with a 
// sum greater than a target value
function smallestSubArrayLen(target, nums) {
// Get the length of the input array
let n = nums.length;
// If the array is empty, return 0
if (n === 0)
return 0;
// Initialize the minimum subarray length to Infinity
let ans = Infinity;
// Create a new array "sums" with size n+1, initialized
// to all zeros
let sums = new Array(n + 1).fill(0);
// Compute the running sum of nums and store it in "sums"
for (let i = 1; i <= n; i++)
sums[i] = sums[i - 1] + nums[i - 1];
// Iterate through each starting index i
for (let i = 1; i <= n; i++) {
// Calculate the target sum for the subarray
// starting at index i
let to_find = target + sums[i - 1];
// Find the first element in "sums" that is >= to_find
let bound = sums.findIndex((element) => element >= to_find);
// If such an element is found and it is not equal to to_find itself
if (bound !== -1 && sums[bound] !== to_find) {
// Compute the length of the subarray and update ans if necessary
let len = bound - (i - 1);
ans = Math.min(ans, len);
}
}
// Return ans if it was updated, otherwise return 0
return (ans !== Infinity) ? ans : 0;
}
  
/* Driver program to test above function */
let arr1 = [1, 4, 45, 6, 10, 19];
let target1 = 51;
console.log("Length of Smallest Subarray: " + smallestSubArrayLen(target1, arr1));
  
let arr2 = [1, 10, 5, 2, 7];
let target2 = 9;
console.log("Length of Smallest Subarray: " + smallestSubArrayLen(target2, arr2));
  
let arr3 = [1, 1, 1, 1, 1, 1, 1, 1];
let target3 = 11;
console.log("Length of Smallest Subarray: " + smallestSubArrayLen(target3, arr3));
  
let arr4 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250];
let target4 = 280;
console.log("Length of Smallest Subarray: " + smallestSubArrayLen(target4, arr4));


Output

Length of Smallest Subarray :3
Length of Smallest Subarray :1
Length of Smallest Subarray :0
Length of Smallest Subarray :4








Time Complexity: O (n log(n)).
Auxiliary Space: O(n)
Thanks to Ankit and Nitin for suggesting this optimized solution. 

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 

 
Asked in: Facebook


Previous Article
Next Article

Similar Reads

Smallest subarray of size greater than K with sum greater than a given value
Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8Output: 2Explanation: Smallest subarray with sum greater than S(=8) is {4, 5}Therefore, the required output is 2. Input: ar
15 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which there are more greater (than a given number K) elements than elements less than or equal to K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray o
3 min read
Length of Smallest subarray in range 1 to N with sum greater than a given value
Given two numbers N and S, the task is to find the length of smallest subarray in range (1, N) such that the sum of those chosen numbers is greater than S. Examples: Input: N = 5, S = 11 Output: 3 Explanation: Smallest subarray with sum &gt; 11 = {5, 4, 3} Input: N = 4, S = 7 Output: 3 Explanation: Smallest subarray with sum &gt; 7 = {4, 3, 2} Naiv
9 min read
Smallest subarray from a given Array with sum greater than or equal to K | Set 2
Given an array A[] consisting of N positive integers and an integer K, the task is to find the length of the smallest subarray with a sum greater than or equal to K. If no such subarray exists, print -1. Examples: Input: arr[] = {3, 1, 7, 1, 2}, K = 11Output: 3Explanation:The smallest subarray with sum ? K(= 11) is {3, 1, 7}. Input: arr[] = {2, 3,
15+ min read
Smallest subarray with sum greater than or equal to K
Given an array A[] consisting of N integers and an integer K, the task is to find the length of the smallest subarray with sum greater than or equal to K. If no such subarray exists, print -1. Examples: Input: A[] = {2, -1, 2}, K = 3 Output: 3 Explanation: Sum of the given array is 3. Hence, the smallest possible subarray satisfying the required co
15+ min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Smallest subarray such that all elements are greater than K
Given an array of N integers and a number K, the task is to find the length of the smallest subarray in which all the elements are greater than K. If there is no such subarray possible, then print -1. Examples: Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5 Output: 1 The subarray is {10} Input: a[] = {1, 2, 3}, K = 13 Output: -1 Approach: The task
4 min read
Smallest subarray having an element with frequency greater than that of other elements
Given an array arr of positive integers, the task is to find the smallest length subarray of length more than 1 having an element occurring more times than any other element. Examples: Input: arr[] = {2, 3, 2, 4, 5} Output: 2 3 2 Explanation: The subarray {2, 3, 2} has an element 2 which occurs more number of times any other element in the subarray
15+ min read
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal
Given an integer K and an array arr[] consisting of N integers, the task is to find the length of the subarray of smallest possible length to be removed such that the count of array elements smaller than and greater than K in the remaining array are equal. Examples: Input: arr[] = {5, 7, 2, 8, 7, 4, 5, 9}, K = 5Output: 2Explanation:Smallest subarra
10 min read
Highest and Smallest power of K less than and greater than equal to N respectively
Given positive integers N and K, the task is to find the highest and smallest power of K greater than equal to and less than equal to N respectively. Examples: Input: N = 3, K = 2 Output: 2 4 Highest power of 2 less than 3 = 2 Smallest power of 2 greater than 3 = 4 Input: N = 6, K = 3 Output: 3 9 Highest power of 3 less than 6 = 3 Smallest power of
5 min read
Count the subarray with sum strictly greater than the sum of remaining elements
Given an array arr[] of N positive integers, the task is to count all the subarrays where the sum of subarray elements is strictly greater than the sum of remaining elements. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 6 Explanation: Subarrays are: {1, 2, 3, 4} - sum of subarray = 10, sum of remaining elements {5} = 5 {1, 2, 3, 4, 5} - sum of
12 min read
Check if a subarray exists with sum greater than the given Array
Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Output: No Explanation: There isn't any subarray of t
7 min read
Largest number less than N with digit sum greater than the digit sum of N
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isn't satisfied for any number then print -1.Examples: Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100I
9 min read
Longest subarray with only one value greater than k
Given an array of N numbers, find length of the longest subarray such that K is the second largest element on insertion. Examples: Input: a[] = {9, 5, 5, 6, 8}, K = 7 Output: 4 The longest subarray is {9, 5, 5, 6}, in which if K is inserted it becomes {9, 5, 5, 6, 7}, and 7 is the second largest element in the array Input: a[] = {9, 5, 5, 6, 8}, K
14 min read
Count of alphabets having ASCII value less than and greater than k
Given a string, the task is to count the number of alphabets having ASCII values less than and greater than or equal to a given integer k. Examples: Input: str = "GeeksForGeeks", k = 90Output:3, 10G, F, G have ascii values less than 90.e, e, k, s, o, r, e, e, k, s have ASCII values greater than or equal to 90 Input: str = "geeksforgeeks", k = 90Out
11 min read
Minimum value to be assigned to the elements so that sum becomes greater than initial sum
Given an array arr[] of N elements, the task is to update all the elements of the given array to some value X such that the sum of all the updated array elements is strictly greater than the sum of all the elements of the initial array and X is the minimum possible. Examples: Input: arr[] = {4, 2, 1, 10, 6} Output: 5 Sum of original array = 4 + 2 +
4 min read
Longest Subarray with Sum greater than Equal to Zero
Given an array of N integers. The task is to find the maximum length subarray such that the sum of all its elements is greater than or equal to 0. Examples: Input: arr[]= {-1, 4, -2, -5, 6, -8} Output: 5 Explanation: {-1, 4, -2, -5, 6} forms the longest subarray with sum=2. Input: arr[]={-5, -6} Output: 0 Explanation: No such subarray is possible A
12 min read
Largest subarray having sum greater than k
Given an array of integers and a value k, find the length of largest subarray having a sum greater than k. Examples: Input : arr[] = {-2, 1, 6, -3}, k = 5Output : 2Largest subarray with sum greater than5 is {1, 6}.Input : arr[] = {2, -3, 3, 2, 0, -1}, k = 3Output : 5Largest subarray with sum greater than3 is {2, -3, 3, 2, 0}.A simple solution is to
14 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Print all pairs from two BSTs whose sum is greater than the given value
Given two Binary Search Tree (BSTs) and a value X, the problem is to print all pairs from both the BSTs whose sum is greater than the given value X.\ Examples: Input: BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18X = 20Output: The pairs are: (3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)Naive Approach
15+ min read
Smallest power of 2 which is greater than or equal to sum of array elements
Given an array of N numbers where values of the array represent memory sizes. The memory that is required by the system can only be represented in powers of 2. The task is to return the size of the memory required by the system.Examples: Input: a[] = {2, 1, 4, 5} Output: 16 The sum of memory required is 12, hence the nearest power of 2 is 16. Input
6 min read
Length of Smallest Subsequence such that sum of elements is greater than equal to K
Given an array arr[] of size N and a number K, the task is to find the length of the smallest subsequence such that the sum of the subsequence is greater than or equal to number K.Example: Input: arr[] = {2, 3, 1, 5, 6, 3, 7, 9, 14, 10, 2, 5}, K = 35 Output: 4 Smallest subsequence with the sum greater than or equal to the given sum K is {7, 9, 14,
6 min read
Smallest number greater than or equal to X whose sum of digits is divisible by Y
Given two integers X and Y, the task is to find the smallest number greater than or equal to X whose sum of digits is divisible by Y. Note: 1 &lt;= X &lt;= 1000, 1 &lt;= Y &lt;= 50.Examples: Input: X = 10, Y = 5 Output: 14 Explanation: 14 is the smallest number greater than 10 whose sum of digits (1+4 = 5) is divisible by 5. Input: X = 5923, Y = 13
7 min read
Smallest number greater than Y with sum of digits equal to X
Given two integers X and Y, find the minimal number with the sum of digits X, which is strictly greater than Y. Examples: Input: X = 18, Y = 99 Output: 189 Explanation: 189 is the smallest number greater than 99 having sum of digits = 18. Input: X = 12, Y = 72 Output: 75 Explanation: 75 is the smallest number greater than 72 that has sum of digits
11 min read
Smallest number greater than or equal to N having sum of digits not exceeding S
Given integer N and integer S, the task is to find the smallest number greater than or equal to N such that the sum of its digits does not exceed S. Examples: Input: N = 3, S = 2Output: 10Explanation: Sum of digits of 10 is 1, which is less than 2. Input: N = 19, S = 3Output: 20Explanation: Sum of digits of 20 is 2, which is less than 3. Approach:
6 min read
Smallest subset with sum greater than all other elements
Given an array of non-negative integers, the task is to find the minimum number of elements such that their sum should be greater than the sum of the rest of the elements of the array. Example: Input: arr[] = [ 3 , 1 , 7, 1 ]Output: 1Explanation: Smallest subset is {7}. Sum of this subset is greater than the sum of all other elements left after rem
6 min read
Minimize operations to make minimum value of one array greater than maximum value of the other
Given two arrays A[] and B[] consisting of N and M integers, the task is to find the minimum number of operations required to make the minimum element of the array A[] at least the maximum element of the array B[] such that in each operation any array element A[] can be incremented by 1 or any array element B[] can be decremented by 1. Examples: In
6 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value | Set 2
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bit wise XOR value is greater than bit wise AND value Examples: Input : arr[]={ 12, 4 , 15}Output: 2Explanation: 12 ^ 4 = 8 , 12 &amp; 4 = 4 . so 12 ^ 4 &gt; 12 &amp; 4 4 ^ 15 = 11, 4 &amp; 15 = 4. so 4 ^ 15 &gt; 4 &amp; 15 . So , above two are valid pa
6 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bitwise XOR value is greater than bitwise AND value Examples: Input : arr[]={ 12, 4, 15}Output: 2Explanation: 12 ^ 4 = 8, 12 &amp; 4 = 4. so 12 ^ 4 &gt; 12 &amp; 4 4 ^ 15 = 11, 4 &amp; 15 = 4. so 4 ^ 15 &gt; 4 &amp; 15 . So, above two are valid pairs {
4 min read
three90RightbarBannerImg