Elements to be added so that all elements of a range are present in array | Java implementation of the approach ; Function to count numbers to be added ; Make a hash of elements and store minimum and maximum element ; Traverse all elements from minimum to maximum and count if it is not in the hash ; Drivers code
import java . util . HashSet ; class GFG { static int countNum ( int arr [ ] , int n ) { HashSet < Integer > s = new HashSet < > ( ) ; int count = 0 , maxm = Integer . MIN_VALUE , minm = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { s . add ( arr [ i ] ) ; if ( arr [ i ] < minm ) minm = arr [ i ] ; if ( arr [ i ] > maxm ) maxm = arr [ i ] ; } for ( int i = minm ; i <= maxm ; i ++ ) if ( ! s . contains ( i ) ) count ++ ; return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 8 , 6 } ; int n = arr . length ; System . out . println ( countNum ( arr , n ) ) ; } }