Last seen array element (last appearance is earliest)
Last Updated :
27 Aug, 2022
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 index stored occurrence, as that will be the one which was last seen while traversing from left to right.
Implementation:
C++
// C++ 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;
}
Java
// Java program to find last seen element in
// an array.
import java.util.*;
class GFG
{
// Returns last seen element in arr[]
static int lastSeenElement(int a[], int n)
{
// Store last occurrence index of
// every element
HashMap<Integer,
Integer> hash = new HashMap<Integer,
Integer>();
for (int i = 0; i < n; i++)
{
hash.put(a[i], i);
}
// Find an element in hash with minimum
// index value
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;
}
// Driver Code
public static void main(String[] args)
{
int a[] = { 2, 1, 2, 2, 4, 1 };
int n = a.length;
System.out.println(lastSeenElement(a, n));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to find last seen
# element in an array.
import sys;
# Returns last seen element in arr[]
def lastSeenElement(a, n):
# Store last occurrence index of
# every element
hash = {}
for i in range(n):
hash[a[i]] = i
# Find an element in hash with minimum
# index value
res_ind = sys.maxsize
res = 0
for x, y in hash.items():
if y < res_ind:
res_ind = y
res = x
return res
# Driver code
if __name__=="__main__":
a = [ 2, 1, 2, 2, 4, 1 ]
n = len(a)
print(lastSeenElement(a,n))
# This code is contributed by rutvik_56
C#
// C# program to find last seen element in
// an array.
using System;
using System.Collections.Generic;
class GFG
{
// Returns last seen element in arr[]
static int lastSeenElement(int []a, int n)
{
// Store last occurrence index of
// every element
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);
}
}
// Find an element in hash with minimum
// index value
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;
}
// Driver Code
public static void Main(String[] args)
{
int []a = { 2, 1, 2, 2, 4, 1 };
int n = a.Length;
Console.WriteLine(lastSeenElement(a, n));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// JavaScript program to find last seen element in
// an array.
// Returns last seen element in arr[]
function lastSeenElement(a, n)
{
// Store last occurrence index of
// every element
let hash = new Map();
for (let i = 0; i < n; i++)
{
hash.set(a[i], i);
}
// Find an element in hash with minimum
// index value
let res_ind = Number.MAX_SAFE_INTEGER, res = 0;
for (let x of hash)
{
if (x[1] < res_ind)
{
res_ind = x[1];
res = x[0];
}
}
return res;
}
// Driver Code
let a = [ 2, 1, 2, 2, 4, 1 ];
let n = a.length;
document.write(lastSeenElement(a, n));
// This code is contributed by gfgking
</script>
Output:
2
Time Complexity: O(n)
Auxiliary Space: O(n), since n extra space has been taken.
Similar Reads
Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
6 min read
Second Largest Element in an Array Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec
14 min read
Least frequent element in an array Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Outp
11 min read
Javascript Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7}Output :Last index: 4Last duplicate item: 6Input :
3 min read
Find first and last positions of an element in a sorted array Given a sorted array arr[] with possibly some duplicates, the task is to find the first and last occurrences of an element x in the given array.Note: If the number x is not found in the array then return both the indices as -1.Examples: Input : arr[] = [1, 3, 5, 5, 5, 5, 67, 123, 125], x = 5Output :
15+ min read
Sort elements by frequency | Set 4 (Efficient approach using hash) Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first. Examples: Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8} Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6} Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8} Output : arr[] = {8,
12 min read