Print the last occurrence of elements in array in relative order
Given an array of N elements, print the elements in the same relative order as given by removing all the occurrences of elements except the last occurrence.
Examples:
Input: a[] = {1, 5, 5, 1, 6, 1}
Output: 5 6 1
Remove two integers 1, which are in the positions 1 and 4. Also, remove the integer 5, which is in the position 2.
Hence the left array is {5, 6, 1}
Input: a[] = {2, 5, 5, 2}
Output: 5 2
Approach:
- Hash the last occurrence of every element.
- Iterate in the array of N elements, if the element’s index is hashed, then print the array element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printLastOccurrence( int a[], int n)
{
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++)
mp[a[i]] = i;
for ( int i = 0; i < n; i++) {
if (mp[a[i]] == i)
cout << a[i] << " " ;
}
}
int main()
{
int a[] = { 1, 5, 5, 1, 6, 1 };
int n = sizeof (a) / sizeof (a[0]);
printLastOccurrence(a, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static void printLastOccurrence( int a[],
int n)
{
HashMap<Integer,
Integer> map = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < n; i++)
map.put(a[i], i);
for ( int i = 0 ; i < n; i++)
{
if (map.get(a[i]) == i)
System.out.print(a[i] + " " );
}
}
public static void main (String[] args)
{
int a[] = { 1 , 5 , 5 , 1 , 6 , 1 };
int n = a.length;
printLastOccurrence(a, n);
}
}
|
Python3
def printLastOccurrence(a, n):
mp = {i: 0 for i in range ( 7 )}
for i in range (n):
mp[a[i]] = i
for i in range (n):
if (mp[a[i]] = = i):
print (a[i], end = " " )
if __name__ = = '__main__' :
a = [ 1 , 5 , 5 , 1 , 6 , 1 ]
n = len (a)
printLastOccurrence(a, n)
|
C#
using System;
class GFG
{
public static void printLastOccurrence( int [] a,
int n)
{
HashMap<Integer,
Integer> map = new HashMap<Integer,
Integer>();
for ( int i = 0; i < n; i++)
map.put(a[i], i);
for ( int i = 0; i < n; i++)
{
if (map. get (a[i]) == i)
Console.Write(a[i] + " " );
}
}
public static void Main ()
{
int [] a = { 1, 5, 5, 1, 6, 1 };
int n = a.Length;
printLastOccurrence(a, n);
}
}
|
PHP
<?php
function printLastOccurrence(& $a , $n )
{
$mp = array ();
for ( $i = 0; $i < $n ; $i ++)
$mp [ $a [ $i ]] = $i ;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $mp [ $a [ $i ]] == $i )
echo $a [ $i ] . " " ;
}
}
$a = array (1, 5, 5, 1, 6, 1);
$n = sizeof( $a );
printLastOccurrence( $a , $n );
?>
|
Javascript
<script>
function printLastOccurrence(a, n)
{
let mp = [];
for (let i = 0; i < n; i++)
mp[a[i]] = i;
for (let i = 0; i < n; i++)
{
if (mp[a[i]] == i)
document.write( a[i] + " " );
}
}
let a = [1, 5, 5, 1, 6, 1];
let n = a.length;
printLastOccurrence(a, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Last Updated :
31 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...