๐ฆ
Count Occurrences
Count Occurrences์ฌ์ ๊ฐ์ฒด +10pts
Problem
Write a function that counts the occurrences of each element in an array.
Examples
Input:
countOccurrences(["a", "b", "a", "c", "a", "b"])Output:
{ a: 3, b: 2, c: 1 }Explanation
์ด ๋ฌธ์ ๋ **๊ฐ์ฒด๋ฅผ ํด์๋งต์ฒ๋ผ ์ฌ์ฉ**ํ์ฌ ๋น๋์๋ฅผ ์ธ๋ ํจํด์ ํ์ตํฉ๋๋ค. ๋ฐ์ดํฐ ๋ถ์๊ณผ ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ์์ ์์ฃผ ์ฌ์ฉ๋ฉ๋๋ค. **ํต์ฌ ํจํด: ๊ฐ์ฒด๋ก ์นด์ดํ ** ๊ฐ์ฒด์ ํค๋ก ์์๋ฅผ, ๊ฐ์ผ๋ก ์ถํ ํ์๋ฅผ ์ ์ฅํฉ๋๋ค. **reduce๋ก ๊ตฌํํ๊ธฐ** ```javascript arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}); ``` **ํต์ฌ ํํ: (acc[item] || 0) + 1** - acc[item]์ด ์กด์ฌํ๋ฉด: ๊ธฐ์กด ๊ฐ...
View detailed explanation โKey Concepts
๊ฐ์ฒด๋ฅผ ํด์๋งต์ผ๋ก ์ฌ์ฉ reduce๋ก ๊ฐ์ฒด ์์ฑ ๋น๋์ ์นด์ดํ
ํจํด || ์ฐ์ฐ์ ํ์ฉ
Time: O(n) Space: O(k)
solution.js
Ctrl + Enter
Run tests to see results here.