![]() |
VOOZH | about |
Given the head of a linked list containing k distinct elements, the task is to return the head of linked list of length k containing the frequency of each distinct element in the given linked list in any order.
Example:
Input: head = {1,2,1,2,3}
Output: {2,2,1}
Explanation: There are 3 distinct elements in the list. The frequency of 1 is 2, the frequency of 2 is 2 and the frequency of 3 is 1. Hence, we return 2 -> 2 -> 1.
Please note that 1 -> 2 -> 2, 2 -> 1 -> 2 and 2 -> 2 -> 1 are also valid answers.Input: head = {1,1,3,3,3}
Output: {2,3}
Explanation: There are 2 distinct elements in the list. The frequency of 1 is 2 and the frequency of 3 is 3. Hence, we return 2 -> 3.
Approach:
Create a hashmap called frequencies to store the frequency of each element. The key is the element, and the value is a ListNode with its frequency. Each ListNode stores its next pointer, so as long as we have a reference to the first node in the sequence, we can maintain the linked list of frequencies.
We create an empty node, freqHead, to store the head of the new linked list of frequencies. We traverse the original linked list, processing the nodes. If the value of current is not yet in the frequencies table, we create a new ListNode with the frequency 1 and add it to the hashmap. If the current's value is already in the hashmap, we increase the node's value by 1 at that key. When we create a new ListNode, we append it to the beginning of the new linked list.
Steps-by-step appraoch:
Below is the implementation of the above approach:
1 3 2
Time complexity: O(n)
Auxiliary Space: O(n)