Given a linked list. Find the first element from the left which appears more than once. If all the elements are unique then print -1.
Input : 1 2 3 4 3 2 1
Output : 1
In this linked list the element 1 occurs two times
and it is the first element to satisfy the condition.
Hence the answer is 1.
Input : 1 2, 3, 4, 5
Output : -1
All the elements are unique. Hence the answer is -1.
- Count the frequency of all the elements of the linked list using a map.
- Now, traverse the linked list again to find the first element from the left whose frequency is greater than 1.
- If no such element exists then print -1.
Below is the implementation of the above approach:
Time Complexity : O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Create new linked list from two given linked list with greater element at each node
- Rearrange a linked list in to alternate first and last element
- Move first element to end of a given Linked List
- Create a linked list from two linked lists by choosing max element at each position
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Check if a linked list is Circular Linked List
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Find first node of loop in a linked list
- Find the product of first k nodes of the given Linked List
- Find first non-repeating character in a given string using Linked List
- Find just strictly greater element from first array for each element in second array
- Find the Second Largest Element in a Linked List
- Find a peak element in Linked List
- Find the element in a linked list with frequency at least N/3
- First common element in two linked lists
- In-place Merge two linked lists without changing links of first list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : andrew1234