Longest Subarray consisting of unique elements from an Array | Java program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return final ans ; Driver Code
import java . util . * ; class GFG { static int largest_subarray ( int a [ ] , int n ) { HashMap < Integer , Integer > index = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 , j = 0 ; i < n ; i ++ ) { j = Math . max ( index . containsKey ( a [ i ] ) ? index . get ( a [ i ] ) : 0 , j ) ; ans = Math . max ( ans , i - j + 1 ) ; index . put ( a [ i ] , i + 1 ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 } ; int n = arr . length ; System . out . print ( largest_subarray ( arr , n ) ) ; } }