Count Occurrences
Count Occurrences - Explanation
Problem Summary
Write a function that counts the occurrences of each element in an array.
Go to Problem →Detailed Explanation
이 문제는 **객체를 해시맵처럼 사용**하여 빈도수를 세는 패턴을 학습합니다. 데이터 분석과 알고리즘 문제에서 자주 사용됩니다. **핵심 패턴: 객체로 카운팅** 객체의 키로 요소를, 값으로 출현 횟수를 저장합니다. **reduce로 구현하기** ```javascript arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}); ``` **핵심 표현: (acc[item] || 0) + 1** - acc[item]이 존재하면: 기존 값 + 1 - acc[item]이 없으면(undefined): 0 + 1 = 1 **["a", "b", "a", "c", "a", "b"] 처리 과정** - "a": {a: 1} - "b": {a: 1, b: 1} - "a": {a: 2, b: 1} - "c": {a: 2, b: 1, c: 1} - "a": {a: 3, b: 1, c: 1} - "b": {a: 3, b: 2, c: 1} **for문 버전** ```javascript const count = {}; for (const item of arr) { count[item] = (count[item] || 0) + 1; } return count; ``` **실용적인 활용** - 문자 빈도수 분석 - 최빈값 찾기 - 데이터 중복 확인
Solution Code
function countOccurrences(arr) {
return arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(k)