Count number of smallest elements in given range in C++


We are given an array of integers of size N. Variables L and R define a range between 1 and N. The goal is to find the number of smallest elements that lie in range L and R such that L>=1 and R<=N.

  • We will do this by traversing the elements that lie in range L and R and find the smallest.

  • Again, traverse the elements of the range L and R and increment count if any element is equal to smallest calculated in step 1.

Let’s understand with examples.

Input − arr[]= { 1,2,3,0,3,2,0,1 }, N=8, L=2, R=5

Output − Count of smallest in range − 1

Explanation

Elements in range L(1) to R(5) are arr[1] to arr[4]. { 2,3,0,3 }. Smallest value is 0. Count of 0 is 1.

Input − arr[]= { 1,2,3,0,3,2,0,1 }, N=8, L=3, R=8

Output − Count of smallest in range − 2

Explanation

Elements in range L(3) to R(8) are arr[2] to arr[7]. { 3,0,3,2,0,1 }. Smallest value is 0. Count of 0 is 2.

Approach used in the below program is as follows

  • We take an integer array arr[] initialized with random numbers.

  • Integers L and R represent the range inside arr[]. Count stores the count of smallest in range L and R.

  • Function countSmallest(int arr[],int n,int l, int r) takes an array, its length, L and R as input and returns the count of smallest in the range.

  • Initialize smallest=arr[l], leftmost element and initial count of smallest as 0.

  • Now if l<0 and r>=n then return 0, invalid range provided.

  • Start traversing the array from index l-1 to r-1. Update smallest if arr[i]<smallest.

  • Again, traverse the array from l-1 to r-1, if arr[i]==smallest, increment count.

  • Return count as desired result.

  • Inside main, display the result present in count.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Function to find if number is prime
int countSmallest(int arr[],int n,int l, int r){
   int smallest=arr[l];
   int count=0;
   if(l<0 && r>=n)
      return 0;
   for(int i=l-1;i<r;i++){
      if(arr[i]<=smallest){
         smallest=arr[i];
      }
   }
   for(int i=l-1;i<r;i++){
      if(arr[i]==smallest){
         ++count;
      }
   }
   return count;
}
int main(){
   int arr[] = { 3,2,1,1,2,3 };
   int n = 6;
   int L,R;
   int count=0;
   L=1,R=5;
   count=countSmallest(arr,n,L,R);
   cout<<endl<<"Count of number of smallest in given range:"<<count;
   L=3,R=4;
   count=countSmallest(arr,n,L,R);
   cout<<endl<<"Count of number of smallest in given range:"<<count;
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of number of smallest in given range:2
Count of number of smallest in given range:2

Updated on: 29-Aug-2020

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements