Last seen array element ( last appearance is earliest ) | C # 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
using System ; using System . Collections . Generic ; class GFG { static int lastSeenElement ( int [ ] a , int n ) { Dictionary < int , int > hash = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . ContainsKey ( a [ i ] ) ) { hash [ a [ i ] ] = i ; } else { hash . Add ( a [ i ] , i ) ; } } int res_ind = int . MaxValue , res = 0 ; foreach ( KeyValuePair < int , int > x in hash ) { if ( x . Value < res_ind ) { res_ind = x . Value ; res = x . Key ; } } return res ; } public static void Main ( String [ ] args ) { int [ ] a = { 2 , 1 , 2 , 2 , 4 , 1 } ; int n = a . Length ; Console . WriteLine ( lastSeenElement ( a , n ) ) ; } }