Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Longest Subarray with Sum greater than Equal to Zero
Next article icon

Length of Smallest subarray in range 1 to N with sum greater than a given value

Last Updated : 05 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 > 11 = {5, 4, 3}

Input: N = 4, S = 7 
Output: 3 
Explanation: 
Smallest subarray with sum > 7 = {4, 3, 2} 
 

Naive Approach: A brute force method is to select elements in reverse order until the sum of all the selected elements is less than or equal to the given number. 

Below is the implementation of the above approach. 

C++




// C++ implementation of the above implementation
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count
// of minimum elements such that
// the sum of those elements is > S.
int countNumber(int N, int S)
{
    int countElements = 0;
    // Initialize currentSum = 0
 
    int currSum = 0;
 
    // Loop from N to 1 to add the numbers
    // and check the condition.
    while (currSum <= S) {
        currSum += N;
        N--;
        countElements++;
    }
 
    return countElements;
}
 
// Driver code
int main()
{
    int N, S;
    N = 5;
    S = 11;
 
    int count = countNumber(N, S);
 
    cout << count << endl;
 
    return 0;
}
 
 

Java




// Java implementation of the above implementation
class GFG
{
 
    // Function to return the count
    // of minimum elements such that
    // the sum of those elements is > S.
    static int countNumber(int N, int S)
    {
        int countElements = 0;
 
        // Initialize currentSum = 0
        int currSum = 0;
     
        // Loop from N to 1 to add the numbers
        // and check the condition.
        while (currSum <= S)
        {
            currSum += N;
            N--;
            countElements++;
        }
        return countElements;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int N, S;
        N = 5;
        S = 11;
     
        int count = countNumber(N, S);
     
        System.out.println(count);
    }
}
 
// This code is contributed by AnkitRai01
 
 

Python




# Python implementation of the above implementation
 
# Function to return the count
# of minimum elements such that
# the sum of those elements is > S.
def countNumber(N, S):
 
    countElements = 0;
    currentSum = 0
 
    currSum = 0;
 
    # Loop from N to 1 to add the numbers
    # and check the condition.
    while (currSum <= S) :
        currSum += N;
        N = N - 1;
        countElements=countElements + 1;
     
    return countElements;
 
# Driver code
N = 5;
S = 11;
count = countNumber(N, S);
print(count) ;
 
# This code is contributed by Shivi_Aggarwal
 
 

C#




// C# implementation of the above implementation
using System;
 
class GFG
{
 
    // Function to return the count
    // of minimum elements such that
    // the sum of those elements is > S.
    static int countNumber(int N, int S)
    {
        int countElements = 0;
 
        // Initialize currentSum = 0
        int currSum = 0;
     
        // Loop from N to 1 to add the numbers
        // and check the condition.
        while (currSum <= S)
        {
            currSum += N;
            N--;
            countElements++;
        }
        return countElements;
    }
     
    // Driver code
    public static void Main()
    {
        int N, S;
        N = 5;
        S = 11;
     
        int count = countNumber(N, S);
     
        Console.WriteLine(count);
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
// JavaScript implementation of the above implementation
 
// Function to return the count
// of minimum elements such that
// the sum of those elements is > S.
function countNumber(N, S)
{
    let countElements = 0;
     
    // Initialize currentSum = 0
    let currSum = 0;
 
    // Loop from N to 1 to add the numbers
    // and check the condition.
    while (currSum <= S)
    {
        currSum += N;
        N--;
        countElements++;
    }
    return countElements;
}
 
// Driver code
    let N, S;
    N = 5;
    S = 11;
    let count = countNumber(N, S);
    document.write(count + "<br>");
 
// This code is contributed by Surbhi Tyagi.
</script>
 
 
Output: 
3

 

Time Complexity: O(N)
Auxiliary Space: O(1), no extra space is required, so it is a constant.
 

Efficient Approach: The idea is to use Binary Search concept to solve the problem. 
From the binary search concept, it is known that the concept can be applied when it is known that there is an order in the problem. That is, for every iteration, if it can be differentiated for sure that the required answer either lies in the first half or second half (i.e), there exists a pattern in the problem.
Therefore, binary search can be applied for the range in the following way:

  1. Initialize start = 1 and end = N.
  2. Find mid = start + (end – start) / 2.
  3. If the sum of all the elements from the last element to mid element is less than or equal to the given sum, then end = mid else start = mid + 1.
  4. Repeat step 2 while start is less than the end.

Below is the implementation of the above approach.

C++




// C++ implementation of the above approach.
 
#include <iostream>
using namespace std;
 
// Function to do a binary search
// on a given range.
int usingBinarySearch(int start, int end,
                      int N, int S)
{
    if (start >= end)
        return start;
    int mid = start + (end - start) / 2;
 
    // Total sum is the sum of N numbers.
    int totalSum = (N * (N + 1)) / 2;
 
    // Sum until mid
    int midSum = (mid * (mid + 1)) / 2;
 
    // If remaining sum is < the required value,
    // then the required number is in the right half
    if ((totalSum - midSum) <= S) {
 
        return usingBinarySearch(start, mid, N, S);
    }
    return usingBinarySearch(mid + 1, end, N, S);
}
 
// Driver code
int main()
{
    int N, S;
 
    N = 5;
    S = 11;
 
    cout << (N - usingBinarySearch(1, N, N, S) + 1)
         << endl;
 
    return 0;
}
 
 

Java




// Java implementation of the above approach.
class GFG
{
     
    // Function to do a binary search
    // on a given range.
    static int usingBinarySearch(int start, int end,
                                int N, int S)
    {
        if (start >= end)
            return start;
        int mid = start + (end - start) / 2;
     
        // Total sum is the sum of N numbers.
        int totalSum = (N * (N + 1)) / 2;
     
        // Sum until mid
        int midSum = (mid * (mid + 1)) / 2;
     
        // If remaining sum is < the required value,
        // then the required number is in the right half
        if ((totalSum - midSum) <= S)
        {
     
            return usingBinarySearch(start, mid, N, S);
        }
        return usingBinarySearch(mid + 1, end, N, S);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int N, S;
     
        N = 5;
        S = 11;
     
        System.out.println(N - usingBinarySearch(1, N, N, S) + 1) ;
    }
}
 
// This code is contributed by AnkitRai01
 
 

Python3




# Python3 implementation of the above approach.
 
# Function to do a binary search
# on a given range.
def usingBinarySearch(start, end, N, S) :
 
    if (start >= end) :
        return start;
         
    mid = start + (end - start) // 2;
 
    # Total sum is the sum of N numbers.
    totalSum = (N * (N + 1)) // 2;
 
    # Sum until mid
    midSum = (mid * (mid + 1)) // 2;
 
    # If remaining sum is < the required value,
    # then the required number is in the right half
    if ((totalSum - midSum) <= S) :
 
        return usingBinarySearch(start, mid, N, S);
     
    return usingBinarySearch(mid + 1, end, N, S);
 
# Driver code
if __name__ == "__main__" :
 
    N = 5;
    S = 11;
 
    print(N - usingBinarySearch(1, N, N, S) + 1) ;
     
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the above approach.
using System;
 
class GFG
{
     
    // Function to do a binary search
    // on a given range.
    static int usingBinarySearch(int start, int end,
                                int N, int S)
    {
        if (start >= end)
            return start;
        int mid = start + (end - start) / 2;
     
        // Total sum is the sum of N numbers.
        int totalSum = (N * (N + 1)) / 2;
     
        // Sum until mid
        int midSum = (mid * (mid + 1)) / 2;
     
        // If remaining sum is < the required value,
        // then the required number is in the right half
        if ((totalSum - midSum) <= S)
        {
     
            return usingBinarySearch(start, mid, N, S);
        }
        return usingBinarySearch(mid + 1, end, N, S);
    }
     
    // Driver code
    public static void Main()
    {
        int N, S;
     
        N = 5;
        S = 11;
     
        Console.WriteLine(N - usingBinarySearch(1, N, N, S) + 1) ;
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
 
// Javascript implementation of the above approach.
 
// Function to do a binary search
// on a given range.
function usingBinarySearch(start, end, N, S)
{
    if (start >= end)
        return start;
         
    let mid = start + (end - start) / 2;
 
    // Total sum is the sum of N numbers.
    let totalSum = (N * (N + 1)) / 2;
 
    // Sum until mid
    let midSum = (mid * (mid + 1)) / 2;
 
    // If remaining sum is < the required value,
    // then the required number is in the right half
    if ((totalSum - midSum) <= S)
    {
        return usingBinarySearch(start, mid, N, S);
    }
    return usingBinarySearch(mid + 1, end, N, S);
}
 
// Driver code
let N, S;
N = 5;
S = 11;
 
document.write((N - usingBinarySearch(
      1, N, N, S) + 1) + "<br>");
 
// This code is contributed by Mayank Tyagi
 
</script>
 
 
Output: 
3

 

Time Complexity: O(log N)
Auxiliary Space: O(N) Where N is recursion stack space.

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Longest Subarray with Sum greater than Equal to Zero
author
rrlinus
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Technical Scripter
  • Binary Search
  • Natural Numbers
  • subarray
  • subarray-sum
  • Technical Scripter 2019
Practice Tags :
  • Arrays
  • Binary Search
  • Mathematical

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
    15 min read
  • Smallest subarray with sum greater than a given value
    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: 3Explanation: Minimum length subarray is [4, 45, 6] Input: x = 100, arr[] = [1, 10, 5, 2, 7]Output: 0Explanation
    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 sma
    15+ 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
    15+ 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} Out
    12 min read
  • Length of smallest subarray to be removed such that the remaining array is sorted
    Given an array arr[] consisting of N integers, the task is to print the length of the smallest subarray to be removed from arr[] such that the remaining array is sorted. Examples: Input: arr[] = {1, 2, 3, 10, 4, 2, 3, 5}Output: 3Explanation:The smallest subarray to be remove is {10, 4, 2} of length
    8 min read
  • Length of smallest Subarray with at least one element repeated K times
    Given an array arr[] of length N and an integer K. The task is to find the minimum length of subarray such that at least one element of the subarray is repeated exactly K times in that subarray. If no such subarray exists, print -1. Examples: Input: arr[] = {1, 2, 1, 2, 1}, K = 2Output: 3Explanation
    9 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[]
    4 min read
  • Length of the smallest subarray with maximum possible sum
    Given an array arr[] consisting of N non-negative integers, the task is to find the minimum length of the subarray whose sum is maximum. Example: Input: arr[] = {0, 2, 0, 0, 12, 0, 0, 0}Output: 4Explanation: The sum of the subarray {2, 0, 0, 12} = 2 + 0 + 0 + 12 = 14, which is maximum sum possible a
    6 min read
  • Length of smallest subarray to be removed to make sum of remaining elements divisible by K
    Given an array arr[] of integers and an integer K, the task is to find the length of the smallest subarray that needs to be removed such that the sum of remaining array elements is divisible by K. Removal of the entire array is not allowed. If it is impossible, then print "-1". Examples: Input: arr[
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences