일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- heap
- codeup
- array
- dfs
- 리트코드
- GenAI
- 자연어처리
- 릿코드
- GenerativeAI
- 파이썬
- Stack
- 파이썬알고리즘
- 투포인터
- Greedy
- SQL
- 알고리즘
- stratascratch
- two-pointer
- nlp
- 파이썬기초100제
- sql코테
- gcp
- Python
- slidingwindow
- 니트코드
- 코드업
- 생성형AI
- 슬라이딩윈도우
- Python3
- LeetCode
Archives
- Today
- Total
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.
'IT > Computer Science' 카테고리의 다른 글
[Neetcode/Array, Binary Search] Binary Search (0) | 2025.07.15 |
---|---|
[Leetcode/Linked List]83. Remove Duplicates from Sorted List (0) | 2025.07.12 |
[Neetcode/Linked List] Reorder Linked List (1) | 2025.07.10 |
[Neetcode/Linked List] Remove Node From End of Linked List (4) | 2025.07.10 |
[Leetcode/Linked List, Two Pointers] 876. Middle of the Linked List (0) | 2025.07.09 |