Given an array arr[] of size n, let min and max be the minimum and maximum elements in the array respectively. Find how many numbers should be added so that every element in the range [min, max] occurs at least once in the array.
Examples:
Input : arr[] = [4, 5, 3, 8, 6]
Output : 1
Explanation: Range is 3-8; only 7 is missing, so count = 1.Input : arr[] = [2, 1, 3]
Output : 0
Explanation: Range is 1-3; no elements are missing, so count = 0.
Table of Content
[Naive Approach] Sorting - O(n log n) Time and O(1) Space
The idea is to first sort the array so that all elements are placed in increasing order. After sorting, traverse the array and compare each element with its next element. If the difference between two consecutive elements is greater than 1, it means some numbers are missing between them, so increase the count by arr[i+1] - arr[i] - 1. Continue this process for all pairs and finally return the total count of missing elements.
#include <bits/stdc++.h>
using namespace std;
// Function to count numbers to be added
int countNum(vector<int>& arr)
{
int count = 0;
// Sort the array
sort(arr.begin(), arr.end());
// Check if elements are consecutive
// or not. If not, update count
for (int i = 0; i < arr.size() - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i + 1] - 1)
count += arr[i + 1] - arr[i] - 1;
return count;
}
int main()
{
vector<int> arr = { 3, 5, 8, 6 };
cout << countNum(arr) << endl;
return 0;
}
import java.io.*;
import java.util.*;
class GfG {
// Function to count numbers to be added
static int countNum(int []arr) {
int count = 0;
// Sort the array
Arrays.sort(arr);
// Check if elements are consecutive
// or not. If not, update count
for (int i = 0; i < arr.length - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i + 1] - 1)
count += arr[i + 1] - arr[i] - 1;
return count;
}
static public void main (String[] args) {
int []arr = { 3, 5, 8, 6 };
System.out.println(countNum(arr));
}
}
# Function to count numbers to be added
def countNum(arr):
count = 0
# Sort the array
arr.sort()
# Check if elements are consecutive
# or not. If not, update count
for i in range(len(arr) - 1):
if arr[i] != arr[i + 1] and \
arr[i] != arr[i + 1] - 1:
count += arr[i + 1] - arr[i] - 1
return count
# Driver Code
if __name__ == "__main__":
arr = [3, 5, 8, 6]
print(countNum(arr))
using System;
class GFG
{
// Function to count numbers to be added
static int countNum(int[] arr)
{
int count = 0;
// Sort the array
Array.Sort(arr);
// Check if elements are consecutive
// or not. If not, update count
for (int i = 0; i < arr.Length - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i + 1] - 1)
count += arr[i + 1] - arr[i] - 1;
return count;
}
static void Main(string[] args)
{
int[] arr = { 3, 5, 8, 6 };
Console.WriteLine(countNum(arr));
}
}
// Function to count numbers to be added
function countNum(arr) {
let count = 0;
// Sort the array
arr.sort((a, b) => a - b);
// Check if elements are consecutive
// or not. If not, update count
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] !== arr[i + 1] && arr[i] !== arr[i + 1] - 1) {
count += arr[i + 1] - arr[i] - 1;
}
}
return count;
}
// Driver Code
const arr = [3, 5, 8, 6];
console.log(countNum(arr));
Output
2
[Expected Approach] Hashing - O(n) Time and O(n) Space
The idea is to insert all array elements into a hash set while simultaneously finding the minimum and maximum values. Since a set stores only unique elements, its size represents the number of distinct elements present in the array. The total number of elements that should exist in the range is (maxm − minm + 1). The difference between this total range size and the set size gives the count of missing elements.
#include <iostream>
#include <vector>
#include <unordered_set>
#include <limits.h>
using namespace std;
// Function to count numbers to be added
int countNum(vector<int> &arr)
{
unordered_set<int> s;
int count = 0, maxm = INT_MIN, minm = INT_MAX;
// Make a hash of elements
// and store minimum and maximum element
for (int i = 0; i < arr.size(); i++) {
s.insert(arr[i]);
if (arr[i] < minm)
minm = arr[i];
if (arr[i] > maxm)
maxm = arr[i];
}
// The missing element count
return (maxm - minm + 1) - s.size();
}
int main()
{
vector<int> arr = { 3, 5, 8, 6 };
cout << countNum(arr) << endl;
return 0;
}
import java.util.HashSet;
class GFG {
// Function to count numbers to be added
public static int countNum(int[] arr) {
HashSet<Integer> s = new HashSet<>();
int maxm = Integer.MIN_VALUE;
int minm = Integer.MAX_VALUE;
// Make a hash of elements
// and store minimum and maximum element
for (int i = 0; i < arr.length; i++) {
s.add(arr[i]);
if (arr[i] < minm)
minm = arr[i];
if (arr[i] > maxm)
maxm = arr[i];
}
// The missing element count
return (maxm - minm + 1) - s.size();
}
public static void main(String[] args) {
int[] arr = { 3, 5, 8, 6 };
System.out.println(countNum(arr));
}
}
# Function to count numbers to be added
def countNum(arr):
s = set()
maxm = float('-inf')
minm = float('inf')
# Make a hash of elements
# and store minimum and maximum element
for num in arr:
s.add(num)
if num < minm:
minm = num
if num > maxm:
maxm = num
# The missing element count
return (maxm - minm + 1) - len(s)
# Driver Code
if __name__ == "__main__":
arr = [3, 5, 8, 6]
print(countNum(arr))
using System;
using System.Collections.Generic;
class GfG
{
// Function to count numbers to be added
public static int countNum(int[] arr)
{
HashSet<int> s = new HashSet<int>();
int maxm = int.MinValue, minm = int.MaxValue;
// Make a hash of elements
// and store minimum and maximum element
foreach (int num in arr)
{
s.Add(num);
if (num < minm)
minm = num;
if (num > maxm)
maxm = num;
}
// The missing element count
return (maxm - minm + 1) - s.Count;
}
static void Main(string[] args)
{
int[] arr = { 3, 5, 8, 6 };
Console.WriteLine(countNum(arr));
}
}
// Function to count numbers to be added
function countNum(arr) {
const s = new Set();
let count = 0, maxm = Number.MIN_SAFE_INTEGER, minm = Number.MAX_SAFE_INTEGER;
// Make a hash of elements
// and store minimum and maximum element
for (let i = 0; i < arr.length; i++) {
s.add(arr[i]);
if (arr[i] < minm)
minm = arr[i];
if (arr[i] > maxm)
maxm = arr[i];
}
// The missing element count
return (maxm - minm + 1) - s.size;
}
// Driver Code
const arr = [3, 5, 8, 6];
console.log(countNum(arr));
Output
2