The Wayback Machine - https://web.archive.org/web/20240710134928/https://www.geeksforgeeks.org/number-subarrays-sum-less-k/
Open In App

Number of subarrays having sum less than K

Last Updated : 19 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of non-negative numbers and a non-negative number k, find the number of subarrays having sum less than k. We may assume that there is no overflow.

Examples :  

Input : arr[] = {2, 5, 6}
        K = 10
Output : 4
The subarrays are {2}, {5}, {6} and
{2, 5},

Input : arr[] = {1, 11, 2, 3, 15}
        K = 10
Output : 4
{1}, {2}, {3} and {2, 3}

A simple solution is to generate all subarrays of the array and then count the number of arrays having sum less than K. 

Below is the implementation of above approach :  

C++




// CPP program to count
// subarrays having sum
// less than k.
#include <bits/stdc++.h>
using namespace std;
 
// Function to find number
// of subarrays having sum
// less than k.
int countSubarray(int arr[],
                  int n, int k)
{
    int count = 0;
 
    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = i; j < n; j++) {
 
            // If sum is less than k
            // then update sum and
            // increment count
            if (sum + arr[j] < k) {
                sum = arr[j] + sum;
                count++;
            }
            else {
                break;
            }
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 11, 2, 3, 15 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    int count = countSubarray(array, size, k);
    cout << count << "\n";
}


Java




// Java program to count subarrays
// having sum less than k.
import java.io.*;
 
class GFG {
 
    // Function to find number of
    // subarrays having sum less than k.
    static int countSubarray(int arr[],
                             int n, int k)
    {
        int count = 0;
 
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
 
                // If sum is less than
                // k then update sum and
                // increment count
                if (sum + arr[j] < k) {
                    sum = arr[j] + sum;
                    count++;
                }
                else {
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int array[] = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.length;
        int count = countSubarray(array, size, k);
        System.out.println(count);
    }
}
 
// This code is contributed by Sam007


Python3




# python program to count subarrays
# having sum less than k.
 
# Function to find number of subarrays
# having sum less than k.
def countSubarray(arr, n, k):
    count = 0
 
    for i in range(0, n):
        sum = 0;
        for j in range(i, n):
             
            # If sum is less than k
            # then update sum and
            # increment count
            if (sum + arr[j] < k):
                sum = arr[j] + sum
                count+= 1
            else:
                break
    return count;
 
 
# Driver Code
array = [1, 11, 2, 3, 15]
k = 10
size = len(array)
count = countSubarray(array, size, k);
print(count)
 
# This code is contributed by Sam007


C#




// C# program to count subarrays
// having sum less than k.
using System;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int[] arr,
                             int n, int k)
    {
        int count = 0;
 
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
 
                // If sum is less than k
                // then update sum and
                // increment count
                if (sum + arr[j] < k) {
                    sum = arr[j] + sum;
                    count++;
                }
                else {
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] array = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.Length;
        int count = countSubarray(array, size, k);
        Console.WriteLine(count);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program to count
// subarrays having sum
// less than k.
 
// Function to find number 
// of subarrays having sum
// less than k.
function countSubarray($arr, $n, $k)
{
    $count = 0;
 
    for ($i = 0; $i < $n; $i++)
    {
    $sum = 0;
        for ($j = $i; $j < $n; $j++)
        {
 
            // If sum is less than
            // k then update sum and
            // increment count
            if ($sum + $arr[$j] < $k)
            {
                $sum = $arr[$j] + $sum;
                $count++;
            }
            else
            {
                break;
            }
        }
    }
 
    return $count;
}
 
// Driver Code
$array = array(1, 11, 2, 3, 15);
$k = 10;
$size = sizeof($array);
$count = countSubarray($array, $size, $k);
echo $count, "\n";
 
// This code is contributed by ajit
?>


Javascript




<script>
// javascript program to count subarrays
// having sum less than k.
 
    // Function to find number of
    // subarrays having sum less than k.
    function countSubarray(arr , n , k)
    {
        var count = 0;
 
        for (i = 0; i < n; i++)
        {
            var sum = 0;
            for (j = i; j < n; j++)
            {
 
                // If sum is less than
                // k then update sum and
                // increment count
                if (sum + arr[j] < k)
                {
                    sum = arr[j] + sum;
                    count++;
                }
                else
                {
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver Code
        var array = [ 1, 11, 2, 3, 15 ];
        var k = 10;
        var size = array.length;
        var count = countSubarray(array, size, k);
        document.write(count);
 
// This code is contributed by Rajput-Ji
</script>


Output

4

Time complexity: O(n^2)
Auxiliary Space: O(1)

An efficient solution is based on a sliding window technique that can be used to solve the problem. We use two pointers start and end to represent starting and ending points of the sliding window. (Not that we need to find contiguous parts).

Initially both start and endpoint to the beginning of the array, i.e. index 0. Now, let’s try to add a new element el. There are two possible conditions.

1st case : 

  • If sum is less than k, increment end by one position. So contiguous arrays this step produce are (end – start). We also add end to previous sum. There are as many such arrays as the length of the window.

2nd case : 

  • If sum becomes greater than or equal to k, this means we need to subtract starting element from sum so that the sum again becomes less than k. So we adjust the window’s left border by incrementing start.
  • We follow the same procedure until end < array size.

Implementation:  

C++




// CPP program to count
// subarrays having sum
// less than k.
#include <bits/stdc++.h>
using namespace std;
 
// Function to find number
// of subarrays having sum
// less than k.
int countSubarrays(int arr[],
                   int n, int k)
{
    int start = 0, end = 0,
        count = 0, sum = arr[0];
 
    while (start < n && end < n) {
 
        // If sum is less than k,
        // move end by one position.
        // Update count and sum
        // accordingly.
        if (sum < k) {
            end++;
 
            if (end >= start)
                count += end - start;
 
            // For last element,
            // end may become n
            if (end < n)
                sum += arr[end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else {
            sum -= arr[start];
            start++;
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 11, 2, 3, 15 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    cout << countSubarrays(array, size, k);
}


Java




// Java program to count
// subarrays having sum
// less than k.
import java.io.*;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int arr[],
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int array[] = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.length;
        int count = countSubarray(array, size, k);
        System.out.println(count);
    }
}
 
// This code is contributed by Sam007


Python 3




# Python 3 program to count subarrays
# having sum less than k.
 
# Function to find number of subarrays
# having sum less than k.
def countSubarrays(arr, n, k):
 
    start = 0
    end = 0
    count = 0
    sum = arr[0]
 
    while (start < n and end < n) :
 
        # If sum is less than k, move end
        # by one position. Update count and
        # sum accordingly.
        if (sum < k) :
            end += 1
 
            if (end >= start):
                count += end - start
 
            # For last element, end may become n
            if (end < n):
                sum += arr[end]
 
        # If sum is greater than or equal to k,
        # subtract arr[start] from sum and
        # decrease sliding window by moving
        # start by one position
        else :
            sum -= arr[start]
            start += 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
     
    array = [ 1, 11, 2, 3, 15 ]
    k = 10
    size = len(array)
    print(countSubarrays(array, size, k))
 
# This code is contributed by ita_c


C#




// C# program to count
// subarrays having sum
// less than k.
using System;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int[] arr,
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] array = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.Length;
        int count = countSubarray(array, size, k);
        Console.WriteLine(count);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program to count
// subarrays having sum
// less than k.
 
// Function to find number
// of subarrays having sum
// less than k.
function countSubarrays($arr,
                       $n, $k)
{
    $start = 0;
    $end = 0;
    $count = 0;
    $sum = $arr[0];
 
    while ($start < $n && $end < $n)
    {
 
        // If sum is less than k,
        // move end by one position.
        // Update count and sum
        // accordingly.
        if ($sum < $k)
        {
            $end++;
 
           if ($end >= $start)
            $count += $end - $start;
 
            // For last element,
            // end may become n
            if ($end < $n)
            $sum += $arr[$end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else
        {
            $sum -= $arr[$start];
            $start++;
        }
    }
 
    return $count;
}
 
    // Driver Code
    $array =array (1, 11, 2, 3, 15);
    $k = 10;
    $size = sizeof($array) ;
    echo countSubarrays($array, $size, $k);
 
// This code is contributed by ajit
?>


Javascript




<script>
 
    // Javascript program to count
    // subarrays having sum
    // less than k.
     
    // Function to find number
    // of subarrays having sum
    // less than k.
    function countSubarray(arr, n, k)
    {
        let start = 0, end = 0;
        let count = 0, sum = arr[0];
  
        while (start < n && end < n) {
  
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
  
                if (end >= start)
                    count += end - start;
  
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
  
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
  
        return count;
    }
     
    let array = [ 1, 11, 2, 3, 15 ];
    let k = 10;
    let size = array.length;
    let count = countSubarray(array, size, k);
    document.write(count);
         
</script>


Output

4

Time complexity: O(n)
Auxiliary Space: O(1)



Similar Reads

Number of subarrays having product less than K
Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K. Examples : Input : arr[] = [1, 2, 3, 4] K = 10Output : 7The subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3} and {2, 3} Input : arr[] = [1, 9, 2, 8, 6, 4, 3] K = 100Output : 16 Input : arr[] = [10, 5, 2, 6] K = 1
13 min read
Find all possible subarrays having product less than or equal to K
Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K. Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ? K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5},
13 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
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
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
Largest subset having with sum less than equal to sum of respective indices
Given an array arr[], the task is to find the length of the largest subset with the sum of elements less than or equal to the sum of its indexes(1-based indexing). Examples: Input: arr[] = {1, 7, 3, 5, 9, 6, 6} Output: 5 Explanation: Largest Subset is {1, 3, 5, 6, 6} Sum of indexes = 1 + 3 + 4 + 6 + 7 = 21 Sum of elements = 1 + 3 + 5 + 6 + 6 = 21 I
8 min read
Number of subarrays having absolute sum greater than K | Set-2
Given an integer array arr[] of length N consisting of both positive and negative integers, the task is to find the number of sub-arrays with the absolute value of sum greater than a given positive number K. Examples: Input : arr[] = {-1, 0, 1}, K = 0 Output : 4 All possible sub-arrays and there total sum: {-1} = -1 {0} = 0 {1} = 1 {-1, 0} = -1 {0,
6 min read
Maximum length L such that the sum of all subarrays of length L is less than K
Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) = 15 &lt; 20. Input: arr[] = {1, 2, 3, 4, 5}, K = 10
8 min read
Find an N-length permutation that contains subarrays with sum less than Bitwise XOR
Given a positive integer N, the task is to find a permutation of length N having Bitwise OR of any of its subarray greater than or equal to the length of the subarray. Examples: Input: N = 5 Output: 1 3 5 2 4 Explanation: Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}. Length of the subarray = 3 Bitwise OR of the subarray = 1
3 min read