Check for each subarray whether it consists of all natural numbers up to its length or not | Java program to implement the above approach ; Function to check if a subarray of size i exists that contain all the numbers in the range [ 1 , i ] ; Store the position of each element of arr [ ] ; Traverse the array ; Insert the position of arr [ i ] ; Store position of each element from the range [ 1 , N ] ; Iterate over the range [ 1 , N ] ; Insert the index of i into st ; Find the smallest element of st ; Find the largest element of st ; If distance between the largest and smallest element of arr [ ] till i - th index is equal to i ; Driver code
import java . util . * ; class GFG { static void checksubarrayExist1_N ( int arr [ ] , int N ) { Map < Integer , Integer > pos = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { pos . put ( arr [ i ] , i ) ; } Set < Integer > st = new HashSet < > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { st . add ( pos . get ( i ) ) ; int Min = Collections . min ( st ) ; int Max = Collections . max ( st ) ; if ( Max - Min + 1 == i ) { System . out . print ( " True ▁ " ) ; } else { System . out . print ( " False ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 3 , 2 } ; int N = arr . length ; checksubarrayExist1_N ( arr , N ) ; } }