VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-linked-list-frequency/

⇱ Create Linked List Frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create Linked List Frequency

Last Updated : 16 May, 2024

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:

  • Initialize a hashmap frequencies to store each element's frequency. The key is the element, and the value is a ListNode with its frequency.
  • Initialize a ListNode current to head for iterating through the original linked list.
  • Initialize a ListNode freqHead to null which will be the head of the linked list of frequencies.
  • Loop through the nodes in the linked list while current != null:
    • If current.val is in frequencies:
      • Set a node, frequencyNode, to the node storing the frequency of element current.val.
      • Increment frequencyNode.val by 1.
    • Otherwise, this is a new element:
      • Create a new ListNode newFrequencyNode with the value 1 and set its next field to freqHead.
      • Set frequencies[current.val] to newFrequencyNode.
      • Set freqHead to newFrequencyNode.
  • Set current to current.next to progress to the next node in the original linked list.
  • Return freqHead.

Below is the implementation of the above approach:


Output
1 3 2 

Time complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags: