Linked List Frequency - Problem
You're given the head of a linked list containing various elements. Your task is to count how many times each distinct element appears and return a new linked list containing these frequency counts.
For example, if your linked list contains [1, 2, 1, 3, 2, 1], you need to:
- Count frequencies:
1appears 3 times,2appears 2 times,3appears 1 time - Return a new linked list with values
[3, 2, 1](in any order)
The order of frequencies in the result doesn't matter - focus on getting the correct counts!
Input & Output
example_1.py โ Basic Example
$
Input:
head = [1,2,1,3,2,1]
โบ
Output:
[3,2,1]
๐ก Note:
Element 1 appears 3 times, element 2 appears 2 times, element 3 appears 1 time. The result can be in any order.
example_2.py โ All Unique Elements
$
Input:
head = [4,5,6]
โบ
Output:
[1,1,1]
๐ก Note:
Each element appears exactly once, so all frequencies are 1.
example_3.py โ Single Element
$
Input:
head = [7]
โบ
Output:
[1]
๐ก Note:
Only one element with frequency 1.
Constraints
- The number of nodes in the list is in the range [0, 104]
- -1000 โค Node.val โค 1000
- The list contains k distinct elements where k โฅ 1
- The result list should contain exactly k nodes
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty hash map and result list pointers
2
Process Elements
For each element: if new, create result node; if seen, update existing node
3
Maintain Mapping
Hash map tracks both frequency count and pointer to corresponding result node
4
Return Result
After single traversal, return head of frequency list
Key Takeaway
๐ฏ Key Insight: By storing both frequency counts AND pointers to result nodes in our hash map, we can update frequencies in real-time during a single traversal, achieving optimal O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code