[LeetCode] Linked List Frequency

3063. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for singly-linked list.
* 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) {
ListNode* runner = head;
unordered_map<int, int> freq;
while(runner) {
freq[runner->val] += 1;
runner = runner->next;
}
runner = head;
vector<int> S;
for(auto& [k,v] : freq) S.push_back(v);
sort(begin(S), end(S));
while(S.size()) {
runner->val = S.back();
S.pop_back();
if(S.size()) runner = runner->next;
}
runner->next = nullptr;
return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/08/PS/LeetCode/linked-list-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.