Tutorialspoint.dev

Last seen array element (last appearance is earliest)

Given an array that might contain duplicates, find the element whose last appearance is latest.

Examples:

Input :  arr[] = {10, 30, 20, 10, 20}
Output : 30
Explanation: Below are indexes of last
appearances of all elements (0 based indexes)
10 last occurs at index 3
30 last occurs at index 1
20 last occurs at index 2
The element whose last appearance earliest
is 30.

Input : arr[] = {20, 10, 20, 20, 40, 10}
Output : 20
Explanation: 
Explanation: Below are indexes of last
appearances of all elements (0 based indexes)
20 last occurs at index 2
10 last occurs at index 5
40 last occurs at index 4
The element whose last appearance earliest
is 20.



A naive approach is to take every element and iterate and compare its last occurrence with other elements. This requires two nested loops, and will take O(n*n) time.
An efficient approach is to use hashing. We store every elements index where it last occurred, and then iterate through all the possible elements and print the element with the least least index stored occurrence, as that will be the one which was last seen while traversing from left to right.

// CPP program to find last seen element in 
// an array.
#include <bits/stdc++.h>
using namespace std;
  
// Returns last seen element in arr[]
int lastSeenElement(int a[], int n)
{
    // Store last occurrence index of 
    // every element
    unordered_map<int, int> hash;
    for (int i = 0; i < n; i++)
        hash[a[i]] = i;
  
    // Find an element in hash with minimum 
    // index value
    int res_ind = INT_MAX, res;
    for (auto x : hash)
    {
       if (x.second < res_ind)
       {
            res_ind = x.second;
            res = x.first;
       }
    }
  
    return res;
}
  
// driver program
int main()
{
    int a[] = { 2, 1, 2, 2, 4, 1 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << lastSeenElement(a, n);
    return 0;
}

Output:

2


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter