925. Linked List Frequency

Given the head of a linked list containing k distinct elements, return the head to a linked list of length k containing the frequency of each distinct element in the given linked list in any order.

Example 1:

Input: head = [1,1,2,1,2,3]

Output: [3,2,1]

Explanation: 

There are 3 distinct elements in the list. The frequency of 1 is 3, the frequency of 2 is 2 and the frequency of 3 is 1. Hence, we return 3 -> 2 -> 1.

Note that 1 -> 2 -> 3, 1 -> 3 -> 2, 2 -> 1 -> 3, 2 -> 3 -> 1, and 3 -> 1 -> 2 are also valid answers.

Example 2:

Input: head = [1,1,2,2,2]

Output: [2,3]

Explanation: 

There are 2 distinct elements in the list. The frequency of 1 is 2 and the frequency of 2 is 3. Hence, we return 2 -> 3.

Now Your Turn!

Pick the correct output for the given input

Input: head = [7,8,7,8]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 1 <= Node.val <= 105



Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
// struct ListNode {
// int val;
// ListNode *next;
// ListNode() : val(0), next(nullptr) {}
// ListNode(int x) : val(x), next(nullptr) {}
// ListNode(int x, ListNode *next) : val(x), next(next) {}
// };
class Solution {
public:
ListNode* frequenciesOfElements(ListNode* head) {
// User code goes here
}
};
Test Case

Input:

Head