Find missing elements of a range
Given an array arr[0..n-1] of distinct elements and a range [low, high], find all numbers that are in range, but not in array. The missing elements should be printed in sorted order.
Examples:
Input: arr[] = {10, 12, 11, 15},
low = 10, hight = 15
Output: 13, 14
Input: arr[] = {1, 14, 11, 51, 15},
low = 50, hight = 55
Output: 50, 52, 53, 54
There can be following two approaches to solve the problem.
- Use Sorting : Sort the array, then do binary search for ‘low’. Once location of low is find, start traversing array from that location and keep printing all missing numbers.
C++
// A sorting based C++ program to find missing// elements from an array#include<bits/stdc++.h>usingnamespacestd;// Print all elements of range [low, high] that// are not present in arr[0..n-1]voidprintMissing(intarr[],intn,intlow,inthigh){// Sort the arraysort(arr, arr+n);// Do binary search for 'low' in sorted// array and find index of first element// which either equal to or greater than// low.int*ptr = lower_bound(arr, arr+n, low);intindex = ptr - arr;// Start from the found index and linearly// search every range element x after this// index in arr[]inti = index, x = low;while(i < n && x<=high){// If x doesn't math with current element// print itif(arr[i] != x)cout << x <<" ";// If x matches, move to next element in arr[]elsei++;// Move to next element in range [low, high]x++;}// Print range elements thar are greater than the// last element of sorted array.while(x <= high)cout << x++ <<" ";}// Driver programintmain(){intarr[] = {1, 3, 5, 4};intn =sizeof(arr)/sizeof(arr[0]);intlow = 1, high = 10;printMissing(arr, n, low, high);return0;}chevron_rightfilter_noneJava
// A sorting based Java program to find missing// elements from an arrayimportjava.util.Arrays;publicclassPrintMissing{// Print all elements of range [low, high] that// are not present in arr[0..n-1]staticvoidprintMissing(intar[],intlow,inthigh){Arrays.sort(ar);// Do binary search for 'low' in sorted// array and find index of first element// which either equal to or greater than// low.intindex = ceilindex(ar, low,0, ar.length -1);intx = low;// Start from the found index and linearly// search every range element x after this// index in arr[]while(index < ar.length && x <= high){// If x doesn't math with current element// print itif(ar[index] != x){System.out.print(x +" ");}// If x matches, move to next element in arr[]elseindex++;// Move to next element in range [low, high]x++;}// Print range elements thar are greater than the// last element of sorted array.while(x <= high){System.out.print(x +" ");x++;}}// Utility function to find ceil index of given elementstaticintceilindex(intar[],intval,intlow,inthigh){if(val < ar[0])return0;if(val > ar[ar.length -1])returnar.length;intmid = (low + high) /2;if(ar[mid] == val)returnmid;if(ar[mid] < val){if(mid +1< high && ar[mid +1] >= val)returnmid +1;returnceilindex(ar, val, mid +1, high);}else{if(mid -1>= low && ar[mid -1] < val)returnmid;returnceilindex(ar, val, low, mid -1);}}// Driver program to test above functionpublicstaticvoidmain(String[] args){intarr[] = {1,3,5,4};intlow =1, high =10;printMissing(arr, low, high);}}// This code is contributed by Rishabh Mahrseechevron_rightfilter_nonePython
# Python library for binary searchfrombisectimportbisect_left# A sorting based C++ program to find missing# elements from an array# Print all elements of range [low, high] that# are not present in arr[0..n-1]defprintMissing(arr,n,low,high):# Sort the arrayarr.sort()# Do binary search for 'low' in sorted# array and find index of first element# which either equal to or greater than# low.ptr=bisect_left(arr,low)index=ptr# Start from the found index and linearly# search every range element x after this# index in arr[]i=indexx=lowwhile(i < nandx <=high):# If x doesn't math with current element# print itif(arr[i] !=x):print(x,end=" ")# If x matches, move to next element in arr[]else:i=i+1# Move to next element in range [low, high]x=x+1# Print range elements thar are greater than the# last element of sorted array.while(x <=high):print(x,end=" ")x=x+1# Driver codearr=[1,3,5,4]n=len(arr)low=1high=10printMissing(arr, n, low, high);# This code is contributed by YatinGuptachevron_rightfilter_noneC#
// A sorting based Java program to// find missing elements from an arrayusingSystem;classGFG{// Print all elements of range// [low, high] that are not// present in arr[0..n-1]staticvoidprintMissing(int[]ar,intlow,inthigh){Array.Sort(ar);// Do binary search for 'low' in sorted// array and find index of first element// which either equal to or greater than// low.intindex = ceilindex(ar, low, 0,ar.Length - 1);intx = low;// Start from the found index and linearly// search every range element x after this// index in arr[]while(index < ar.Length && x <= high){// If x doesn't math with current// element print itif(ar[index] != x){Console.Write(x +" ");}// If x matches, move to next// element in arr[]elseindex++;// Move to next element in// range [low, high]x++;}// Print range elements thar// are greater than the// last element of sorted array.while(x <= high){Console.Write(x +" ");x++;}}// Utility function to find// ceil index of given elementstaticintceilindex(int[]ar,intval,intlow,inthigh){if(val < ar[0])return0;if(val > ar[ar.Length - 1])returnar.Length;intmid = (low + high) / 2;if(ar[mid] == val)returnmid;if(ar[mid] < val){if(mid + 1 < high && ar[mid + 1] >= val)returnmid + 1;returnceilindex(ar, val, mid + 1, high);}else{if(mid - 1 >= low && ar[mid - 1] < val)returnmid;returnceilindex(ar, val, low, mid - 1);}}// Driver CodestaticpublicvoidMain (){int[]arr = { 1, 3, 5, 4 };intlow = 1, high = 10;printMissing(arr, low, high);}}// This code is contributed// by Sach_Codechevron_rightfilter_none
Output:2 6 7 8 9 10
- Use Hashing : Create a hash table and insert all array items into the hash table. Once all items are in hash table, traverse through the range and print all missing elements.
C++
// A hashing based C++ program to find missing// elements from an array#include<bits/stdc++.h>usingnamespacestd;// Print all elements of range [low, high] that// are not present in arr[0..n-1]voidprintMissing(intarr[],intn,intlow,inthigh){// Insert all elements of arr[] in setunordered_set<int> s;for(inti=0; i<n; i++)s.insert(arr[i]);// Traverse throught the range an print all// missing elementsfor(intx=low; x<=high; x++)if(s.find(x) == s.end())cout << x <<" ";}// Driver programintmain(){intarr[] = {1, 3, 5, 4};intn =sizeof(arr)/sizeof(arr[0]);intlow = 1, high = 10;printMissing(arr, n, low, high);return0;}chevron_rightfilter_noneJava
// A hashing based Java program to find missing// elements from an arrayimportjava.util.Arrays;importjava.util.HashSet;publicclassPrint{// Print all elements of range [low, high] that// are not present in arr[0..n-1]staticvoidprintMissing(intar[],intlow,inthigh){HashSet<Integer> hs =newHashSet<>();// Insert all elements of arr[] in setfor(inti =0; i < ar.length; i++)hs.add(ar[i]);// Traverse throught the range an print all// missing elementsfor(inti = low; i <= high; i++){if(!hs.contains(i)){System.out.print(i +" ");}}}// Driver program to test above functionpublicstaticvoidmain(String[] args){intarr[] = {1,3,5,4};intlow =1, high =10;printMissing(arr, low, high);}}// This code is contributed by Rishabh Mahrseechevron_rightfilter_nonePython3
# A hashing based Python 3 program to# find missing elements from an array# Print all elements of range# [low, high] that are not# present in arr[0..n-1]defprintMissing(arr, n, low, high):# Insert all elements of# arr[] in sets=set(arr)# Traverse through the range# and print all missing elementsforxinrange(low, high+1):ifxnotins:print(x, end=' ')# Driver Codearr=[1,3,5,4]n=len(arr)low, high=1,10printMissing(arr, n, low, high)# This code is contributed# by SamyuktaSHegdechevron_rightfilter_noneC#
// A hashing based C# program to// find missing elements from an arrayusingSystem;usingSystem.Collections.Generic;classGFG{// Print all elements of range// [low, high] that are not// present in arr[0..n-1]staticvoidprintMissing(int[]arr,intn,intlow,inthigh){// Insert all elements of arr[] in setHashSet<int> s =newHashSet<int>();for(inti = 0; i < n; i++){s.Add(arr[i]);}// Traverse throught the range// an print all missing elementsfor(intx = low; x <= high; x++)if(!s.Contains(x))Console.Write(x +" ");}// Driver CodepublicstaticvoidMain(){int[]arr = {1, 3, 5, 4};intn = arr.Length;intlow = 1, high = 10;printMissing(arr, n, low, high);}}// This code is contributed by ihritikchevron_rightfilter_none
Output:2 6 7 8 9 10
Which approach is better?
Time complexity of first approach is O(nLogn + k) where k is number of missing elements (Note that k may be more than nLogn if array is small and range is big)
Time complexity of second solution is O(n + (high-low+1)).
If the given array has almost elements of range i.e., n is close to value of (high-low+1), then second approach is definitely better as there is no Log n factor. But if n is much smaller than range, then first approach is better as it doesn’t require extra space for hashing. We can also modify first approach to print adjacent missing elements as range to save time. For example if 50, 51, 52, 53, 54, 59 are missing, we can print them as 50-54, 59 in first method. And if printing this way is allowed, the first approach takes only O(n Log n) time.
This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Print missing elements that lie in range 0 - 99
- Find the one missing number in range
- Find the missing number in a sorted array of limited range
- Find missing elements from an Array
- Find the missing elements from 1 to M in given N ranges
- Find four missing numbers in an array containing elements from 1 to N
- Find smallest range containing elements from k lists
- Find array elements with frequencies in range [l , r]
- Find duplicates in a given array when elements are not limited to a range
- Find even occurring elements in an array of limited range
- Elements to be added so that all elements of a range are present in array
- Find the Missing Number
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Find the Missing Number in a sorted array
- Find the repeating and the missing | Added 3 new methods



