Smallest subarray with sum greater than a given value
Last Updated :
23 Jul, 2025
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
// Java program to find smallest
// subarray with sum greater than x
import java.util.*;
class GfG {
// Returns length of smallest subarray
// with sum greater than x. If no such
// subarray exists, returns 0.
static int smallestSubWithSum(int x, int[] arr) {
int n = arr.length;
int res = Integer.MAX_VALUE;
// 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 = Math.min(res, j - i + 1);
break;
}
}
}
// Return 0 if answer does
// not exists.
if (res == Integer.MAX_VALUE) return 0;
return res;
}
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
System.out.println(smallestSubWithSum(x, arr));
}
}
Python
# Python program to find smallest
# subarray with sum greater than x
# Returns length of smallest subarray
# with sum greater than x. If no such
# subarray exists, returns 0.
def smallestSubWithSum(x, arr):
n = len(arr)
res = float('inf')
# Pick every element as starting point
for i in range(n):
curr = 0
for j in range(i, n):
curr += arr[j]
if curr > x:
res = min(res, j - i + 1)
break
# Return 0 if answer does
# not exists.
if res == float('inf'):
return 0
return res
if __name__ == "__main__":
arr = [1, 4, 45, 6, 10, 19]
x = 51
print(smallestSubWithSum(x, arr))
C#
// C# program to find smallest
// subarray with sum greater than x
using System;
class GfG {
// Returns length of smallest subarray
// with sum greater than x. If no such
// subarray exists, returns 0.
static int smallestSubWithSum(int x, int[] arr) {
int n = arr.Length;
int res = int.MaxValue;
// 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 = Math.Min(res, j - i + 1);
break;
}
}
}
// Return 0 if answer does
// not exists.
if (res == int.MaxValue) return 0;
return res;
}
static void Main(string[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
Console.WriteLine(smallestSubWithSum(x, arr));
}
}
Javascript
// JavaScript program to find smallest
// subarray with sum greater than x
// Returns length of smallest subarray
// with sum greater than x. If no such
// subarray exists, returns 0.
function smallestSubWithSum(x, arr) {
let n = arr.length;
let res = Infinity;
// Pick every element as starting point
for (let i = 0; i < n; i++) {
let curr = 0;
for (let j = i; j < n; j++) {
curr += arr[j];
if (curr > x) {
res = Math.min(res, j - i + 1);
break;
}
}
}
// Return 0 if answer does
// not exists.
if (res === Infinity) return 0;
return res;
}
//driver code
let arr = [1, 4, 45, 6, 10, 19];
let x = 51;
console.log(smallestSubWithSum(x, arr));
[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
// Java program to find smallest
// subarray with sum greater than or equal to x
import java.util.*;
class GfG {
// Returns the length of the smallest subarray
// with sum greater than or equal to x
static int smallestSubWithSum(int x, int[] arr) {
int n = arr.length;
int res = Integer.MAX_VALUE;
int[] preSum = new int[n + 1];
// 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] + 1;
// Find the first prefix sum > target
int bound = Arrays.binarySearch(preSum, toFind);
if (bound < 0) {
bound = -(bound + 1);
}
if (bound <= n) {
int len = bound - (i - 1);
res = Math.min(res, len);
}
}
// If subarray does not exists
if (res == Integer.MAX_VALUE) return 0;
return res;
}
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
System.out.println(smallestSubWithSum(x, arr));
}
}
Python
# Python program to find smallest
# subarray with sum greater than or equal to x
from bisect import bisect_left
# Returns the length of the smallest subarray
# with sum greater than or equal to x
def smallestSubWithSum(x, arr):
n = len(arr)
res = float('inf')
preSum = [0] * (n + 1)
# Compute the prefix sums
for i in range(1, n + 1):
preSum[i] = preSum[i - 1] + arr[i - 1]
# Iterate through each starting index
for i in range(1, n + 1):
# Target sum for current subarray
toFind = x + preSum[i - 1] + 1
# Find the first prefix sum > target
bound = bisect_left(preSum, toFind)
if bound <= n:
len_sub = bound - (i - 1)
res = min(res, len_sub)
# If subarray does not exists
if res == float('inf'):
return 0
return res
if __name__ == "__main__":
arr = [1, 4, 45, 6, 10, 19]
x = 51
print(smallestSubWithSum(x, arr))
C#
// C# program to find smallest
// subarray with sum greater than or equal to x
using System;
class GfG {
// Returns the length of the smallest subarray
// with sum greater than or equal to x
static int smallestSubWithSum(int x, int[] arr) {
int n = arr.Length;
int res = int.MaxValue;
int[] preSum = new int[n + 1];
// 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] + 1;
// Find the first prefix sum > target
int bound = Array.BinarySearch(preSum, toFind);
if (bound < 0) {
bound = ~bound;
}
if (bound <= n) {
int len = bound - (i - 1);
res = Math.Min(res, len);
}
}
// If subarray does not exists
if (res == int.MaxValue) return 0;
return res;
}
static void Main(string[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
Console.WriteLine(smallestSubWithSum(x, arr));
}
}
JavaScript
// JavaScript program to find smallest
// subarray with sum greater than or equal to x
// Returns the length of the smallest subarray
// with sum greater than or equal to x
function smallestSubWithSum(x, arr) {
let n = arr.length;
let res = Infinity;
let preSum = new Array(n + 1).fill(0);
// Compute the prefix sums
for (let i = 1; i <= n; i++) {
preSum[i] = preSum[i - 1] + arr[i - 1];
}
// Iterate through each starting index
for (let i = 1; i <= n; i++) {
// Target sum for current subarray
let toFind = x + preSum[i - 1] + 1;
// Find the first prefix sum > target
let bound = preSum.findIndex(val => val >= toFind);
if (bound !== -1) {
let len = bound - (i - 1);
res = Math.min(res, len);
}
}
// If subarray does not exists
if (res === Infinity) return 0;
return res;
}
//driver code
let arr = [1, 4, 45, 6, 10, 19];
let x = 51;
console.log(smallestSubWithSum(x, arr));
[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
// Java program to find smallest
// subarray with sum greater than x
import java.util.*;
class GfG {
// Returns the length of the smallest subarray
// with sum greater than or equal to x
static int smallestSubWithSum(int x, int[] arr) {
int i = 0, j = 0;
int sum = 0;
int ans = Integer.MAX_VALUE;
while (j < arr.length) {
// Expand window until sum > x
// or end of array reached
while (j < arr.length && sum <= x) {
sum += arr[j++];
}
// If we reached end of array and sum
// still <= x, no valid subarray exists
if (j == arr.length && sum <= x) break;
// Minimize window from start
// while maintaining sum > x
while (i < j && sum - arr[i] > x) {
sum -= arr[i++];
}
ans = Math.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 == Integer.MAX_VALUE) return 0;
return ans;
}
public static void main(String[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
System.out.println(smallestSubWithSum(x, arr));
}
}
Python
# Python program to find smallest
# subarray with sum greater than x
# Returns the length of the smallest subarray
# with sum greater than or equal to x
def smallestSubWithSum(x, arr):
i, j = 0, 0
sum = 0
ans = float('inf')
while j < len(arr):
# Expand window until sum > x
# or end of array reached
while j < len(arr) and sum <= x:
sum += arr[j]
j += 1
# If we reached end of array and sum
# still <= x, no valid subarray exists
if j == len(arr) and sum <= x:
break
# Minimize window from start
# while maintaining sum > x
while i < j and sum - arr[i] > x:
sum -= arr[i]
i += 1
ans = min(ans, j - i)
# Remove current start
# element and shift window
sum -= arr[i]
i += 1
# Return 0 if no valid subarray
# found, else return min length
if ans == float('inf'):
return 0
return ans
if __name__ == "__main__":
arr = [1, 4, 45, 6, 10, 19]
x = 51
print(smallestSubWithSum(x, arr))
C#
// C# program to find smallest
// subarray with sum greater than x
using System;
class GfG {
// Returns the length of the smallest subarray
// with sum greater than or equal to x
static int smallestSubWithSum(int x, int[] arr) {
int i = 0, j = 0;
int sum = 0;
int ans = int.MaxValue;
while (j < arr.Length) {
// Expand window until sum > x
// or end of array reached
while (j < arr.Length && sum <= x) {
sum += arr[j++];
}
// If we reached end of array and sum
// still <= x, no valid subarray exists
if (j == arr.Length && sum <= x) break;
// Minimize window from start
// while maintaining sum > x
while (i < j && sum - arr[i] > x) {
sum -= arr[i++];
}
ans = Math.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.MaxValue) return 0;
return ans;
}
static void Main(string[] args) {
int[] arr = {1, 4, 45, 6, 10, 19};
int x = 51;
Console.WriteLine(smallestSubWithSum(x, arr));
}
}
Javascript
// JavaScript program to find smallest
// subarray with sum greater than x
// Returns the length of the smallest subarray
// with sum greater than or equal to x
function smallestSubWithSum(x, arr) {
let i = 0, j = 0;
let sum = 0;
let ans = Infinity;
while (j < arr.length) {
// Expand window until sum > x
// or end of array reached
while (j < arr.length && sum <= x) {
sum += arr[j++];
}
// If we reached end of array and sum
// still <= x, no valid subarray exists
if (j === arr.length && sum <= x) break;
// Minimize window from start
// while maintaining sum > x
while (i < j && sum - arr[i] > x) {
sum -= arr[i++];
}
ans = Math.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 === Infinity) return 0;
return ans;
}
//driver code
let arr = [1, 4, 45, 6, 10, 19];
let x = 51;
console.log(smallestSubWithSum(x, arr));
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem