Linked List Frequency - Problem
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.
The frequency of an element is the number of times it appears in the linked list.
Example: If the linked list is [1→2→1→3→2→2], the frequencies are: 1 appears 2 times, 2 appears 3 times, 3 appears 1 time. Return a linked list containing [2→3→1] (frequencies in any order).
Input & Output
Example 1 — Basic Case
$
Input:
head = [1,2,1,3,2,2]
›
Output:
[2,3,1]
💡 Note:
Element 1 appears 2 times, element 2 appears 3 times, element 3 appears 1 time. Return frequencies in any order.
Example 2 — All Unique
$
Input:
head = [1,2,3]
›
Output:
[1,1,1]
💡 Note:
Each element appears exactly once, so all frequencies are 1.
Example 3 — All Same
$
Input:
head = [5,5,5,5]
›
Output:
[4]
💡 Note:
Only one distinct element (5) appears 4 times, so return [4].
Constraints
- 1 ≤ length of linked list ≤ 105
- -105 ≤ Node.val ≤ 105
- The linked list contains exactly k distinct elements
Visualization
Tap to expand
Understanding the Visualization
1
Input List
Linked list with repeated elements: [1,2,1,3,2,2]
2
Count Frequencies
Count how many times each element appears
3
Output List
New linked list with frequency counts: [2,3,1]
Key Takeaway
🎯 Key Insight: Use hash map to count frequencies in single pass, then build result linked list
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code