VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-subarrays-sum-less-k/

⇱ Subarrays having sum less than K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subarrays having sum less than K

Last Updated : 4 Apr, 2026

Given an array arr[] 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
Explanation: The subarrays are [2], [5], [6], and [2, 5]

Input: arr[] = [1, 11, 2, 3, 15], K = 10
Output: 4
Explanation: The subarrays are [1], [2], [3], and [2, 3]

Naive Approach - O(n²) Time and O(1) Space

Check every possible subarray and compute its sum. For each starting index, extend the subarray one element at a time and count it if the sum is less than K. Stop extending when the sum becomes greater than or equal to K since it will only increase further.

Steps:

  • Run a loop from 0 to n-1 to select the starting index of the subarray
  • For each starting index, run another loop from i to n-1 to select the ending index
  • Maintain a variable sum to store the current subarray sum
  • Add elements one by one to sum
  • If sum < K, increment the count
  • If sum ≥ K, break the inner loop (since all elements are non-negative) 

Output
4

Sliding Window - O(n) Time and O(1) Space

The idea of this approach is to use two pointers, start and end, to form a window (subarray). This window expands when we move end forward and shrinks when we move start forward, so that the sum of elements inside the window always remains less than K.

Steps

  • Start with start = 0, sum = 0, and count = 0
  • Move end step by step and keep adding the current element to sum
  • If the sum becomes equal to or greater than K, remove elements from the beginning by subtracting arr[start] and moving start forward
  • Keep removing elements until the sum becomes less than K again
  • Now the current window has sum less than K
  • Count all subarrays that end at end by adding (end - start + 1) to count

Output
4
Comment
Article Tags:
Article Tags: