Last seen array element ( last appearance is earliest ) | Java program to find last seen element in an array . ; Returns last seen element in arr [ ] ; Store last occurrence index of every element ; Find an element in hash with minimum index value ; Driver Code
import java . util . * ; class GFG { static int lastSeenElement ( int a [ ] , int n ) { HashMap < Integer , Integer > hash = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { hash . put ( a [ i ] , i ) ; } int res_ind = Integer . MAX_VALUE , res = 0 ; for ( Map . Entry < Integer , Integer > x : hash . entrySet ( ) ) { if ( x . getValue ( ) < res_ind ) { res_ind = x . getValue ( ) ; res = x . getKey ( ) ; } } return res ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 1 , 2 , 2 , 4 , 1 } ; int n = a . length ; System . out . println ( lastSeenElement ( a , n ) ) ; } }