Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Last Appearance

Moderate
0/80
Average time to solve is 38m
profile
Contributed by
44 upvotes
Asked in companies
AdobeVisaOracle

Problem statement

You are given an unsorted Singly Linked List with 'N' nodes which may contain duplicate elements. You are supposed to remove all duplicate elements from the linked list and keep only the last appearance of elements.

Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of the input contains the elements of the singly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
Output format :
Print a single line containing updated list elements separated by a single space.
Note:
You are not required to print the output, it has already been taken care of. Just implement the function.
Constraints :
0 <= N <= 5 * 10^5
-10^9 <= data <= 10^9 and data != -1

Where 'data' is the value of elements that exist in the linked list.

Time limit: 1 sec
Sample Input 1:
7 11 13 23 7 11 13 -1
Sample Output 1:
23 7 11 13 -1
Explanation of Sample Input 1:
7, 11, and 13 have appeared two times, so we remove the first appearance of 7, 11, and 13 and keep their last appearance. Since 7, 11 and 13 are removed, so now the head of the modified, linked list becomes 23.
Sample Input 2:
13 1 19 3 9 -1
Sample Output 2:
13 1 19 3 9 -1
Explanation of Sample Input 2:
There are no duplicate elements in the given linked list, so there will be no elements deleted. And the modified linked list will be the same as the given linked list.
Full screen
Console