- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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. *

**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.

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.

**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.

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

The number of elements required to complete the range is 1

- Related Questions & Answers
- Count numbers in a range that are divisible by all array elements in C++
- Find the minimum value to be added so that array becomes balanced in C++
- Print elements that can be added to form a given sum
- Find minimum value to assign all array elements so that array product becomes greater in C++
- Maximum difference elements that can added to a set in C++
- Count array elements that divide the sum of all other elements in C++
- Find a range that covers all the elements of given N ranges in C++
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph in C++
- Total number of elements present in an array in C#
- Check if an array contains all elements of a given range in Python
- Find array elements that are out of order in JavaScript
- Find missing elements of a range in C++
- Find duplicates in a given array when elements are not limited to a range in C++
- Find elements which are present in first array and not in second in C++
- Rearrange array such that even index elements are smaller and odd index elements are greater in C++

Advertisements