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: 1 appears 3 times, 2 appears 2 times, 3 appears 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
Linked List Frequency CounterTransform [1,2,1,3,2,1] โ†’ [3,2,1] in one passHash Map State(Key โ†’ Freq, Node*)1 โ†’ frequency: 3 node: *result12 โ†’ frequency: 2 node: *result23 โ†’ frequency: 1 node: *result3Live Updates!Points toresult nodesResult Linked List(Built during traversal)321nullValues updated in real-time!๐Ÿš€ Algorithm Benefits:โœ“ Single pass through input: O(n) time complexityโœ“ Space efficient: O(k) where k = distinct elements โ‰ค nโœ“ Real-time updates: no need for second passโœ“ Direct result construction during counting phase
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.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25
42.4K Views
Medium-High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen