Find the missing elements from 1 to M in given N ranges | Java program to find missing elements from given Ranges ; Function to find missing elements from given Ranges ; First of all sort all the given ranges ; Store ans in a different vector ; prev is use to store end of last range ; j is used as a counter for ranges ; For last segment ; Finally print all answer ; Driver code ; Store ranges in vector of pair
import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findMissingNumber ( ArrayList < Pair > ranges , int m ) { Collections . sort ( ranges , new Comparator < Pair > ( ) { public int compare ( Pair first , Pair second ) { if ( first . first == second . first ) { return first . second - second . second ; } return first . first - second . first ; } } ) ; ArrayList < Integer > ans = new ArrayList < > ( ) ; int prev = 0 ; for ( int j = 0 ; j < ranges . size ( ) ; j ++ ) { int start = ranges . get ( j ) . first ; int end = ranges . get ( j ) . second ; for ( int i = prev + 1 ; i < start ; i ++ ) ans . add ( i ) ; prev = end ; } for ( int i = prev + 1 ; i <= m ; i ++ ) ans . add ( i ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans . get ( i ) <= m ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 2 , M = 6 ; ArrayList < Pair > ranges = new ArrayList < > ( ) ; ranges . add ( new Pair ( 1 , 2 ) ) ; ranges . add ( new Pair ( 4 , 5 ) ) ; findMissingNumber ( ranges , M ) ; } }