Elements to be added so that all elements of a range are present in array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] consisting of n number. Our task is to create a program to find the number of elements to be added so that all elements of a range are present in array. 

Problem Description: Here, we need to find the number of elements that are needed to be added to the array to make sure that all elements of a range are present in the array. The range is from smallestElement of array to largestElement of array. 

Let’s take an example to understand the problem,

Input: arr[] = {5, 8, 3, 1, 6, 2}

Output: 2

Explanation:

The range is from 1 to 8,

Elements to be added are 4 and 7.

Solution Approach −

A simple solution to the problem is by finding which element of the range that is not present in the array. For this, we need to sort the array and then find if the next element is present or not.

Algorithm −

Step 1: sort the array.

Step 2: loop through the array, for i -> 0 to n-1.

Step 2.1: if arr[i] + 1 != arr[i+1], increase count.

Step 3: print count.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int calcEleRequired(int arr[], int n)
{
   int count = 0;
   sort(arr, arr + n);
   for (int i = 0; i < n - 1; i++)
      if (arr[i]+1 != arr[i+1] )
         count ++;

   return count;
}

int main()
{
   int arr[] = { 5, 7, 3, 1, 6, 2 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The number of elements required to complete the range is "<<calcEleRequired(arr, n);
   return 0;
}

Output −

The number of elements required to complete the range is 1
raja
Published on 22-Jan-2021 12:40:32
Advertisements