Given a linked list that contains some random integers from 1 to n with many duplicates. Replace each duplicate element that is present in the linked list with the values n+1, n+2, n+3 and so on(starting from left to right in the given linked list).
Input : 1 3 1 4 4 2 1 Output : 1 3 5 4 6 2 7 Replace 2nd occurrence of 1 with 5 i.e. (4+1) 2nd occurrence of 4 with 6 i.e. (4+2) 3rd occurrence of 1 with 7 i.e. (4+3) Input : 1 1 1 4 3 2 2 Output : 1 5 6 4 3 2 7
1. Traverse the linked list, store the frequencies of every number present in linked list in a map and alongwith it find the maximum integer present in linked list i.e. maxNum.
2. Now, traverse the linked list again and if the frequency of any number is more than 1, set its value to -1 in map on its first occurrence.
3.The reason for this is that on next occurrence of this number we will find its value -1 which means this number has occurred before, change its data with maxNum + 1 and increment maxNum.
Below is the implementation of idea.
Linked list before replacing duplicates 1 3 1 4 4 2 1 Linked list after replacing duplicates 1 3 5 4 6 2 7
This article is contributed by Chhavi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Replace even nodes of a doubly linked list with the elements of array
- Delete N nodes after M nodes of a linked list
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Remove duplicates from an unsorted linked list
- Remove duplicates from a sorted linked list
- Remove all occurrences of duplicates from a sorted Linked List
- Remove duplicates from a sorted doubly linked list
- Remove duplicates from an unsorted doubly linked list
- Remove duplicates from a sorted linked list using recursion
- Merge two sorted linked list without duplicates
- Count duplicates in a given linked list
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Replace each node with its Surpasser Count in Linked List
- Replace every node of a Linked list with the greatest element on right side
- 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