Tech for good

[Leetcode/Linked List, Hash Table] 3063. Linked List Frequency 본문

IT/Computer Science

[Leetcode/Linked List, Hash Table] 3063. Linked List Frequency

Diana Kang 2025. 7. 13. 00:23

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]:
        values = []
        curr = head

        while curr:
            values.append(curr.val)
            curr = curr.next

        freq = Counter(values)

        dummy = ListNode(0)
        tail = dummy   # tail starts at dummy
        for count in freq.values():
            tail.next = ListNode(count)
            tail = tail.next

        return dummy.next   # return the real head

(+) 🔍 defaultdict() vs Counter()

defaultdict(int) Counter()
Flexible dictionary with default values for missing keys Specialized for count things
Any type (e.g., int, list) Always uses int as default

 

Counter() in Python

Counter is a special dictionary subclass from Python’s collections module, designed specifically for counting the frequency of elements in an iterable like a list, string, or tuple.

from collections import Counter

Counter(['a', 'b', 'a', 'c', 'b', 'a'])
# Output: Counter({'a': 3, 'b': 2, 'c': 1})

(+)  ListNode() vs ListNode(0)

dummy = ListNode()     # val defaults to 0
dummy = ListNode(0)    # explicitly sets val to 0

 

because ListNode is defined as:

def __init__(self, val=0, next=None):

 

So if you don’t pass any arguments, val will default to 0, and next to None.

 

✅ Why use tail?

  • The variable tail in this code is used to help build a new linked list easily and cleanly by keeping track of the last node as you append new nodes.
  • In other words, tail is a convenient way to append nodes one by one while keeping dummy at the beginning for returning the final list.