Elements to be added so that all elements of a range are present in array | C # 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
using System ; using System . Collections . Generic ; class GFG { static int countNum ( int [ ] arr , int n ) { HashSet < int > s = new HashSet < int > ( ) ; int count = 0 , maxm = int . MinValue , minm = int . MaxValue ; 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 ; Console . WriteLine ( countNum ( arr , n ) ) ; } }