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 > 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

3

Time Complexity: O(N)

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

3

Time Complexity: O(log N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Shivi_Aggarwal, AnkitRai01