๐ ์๊ฐ๋ณต์ก๋ ๋ถ์๊ณผ ์ฑ๋ฅ ๋น๊ต
๐ก ์๊ฐ๋ณต์ก๋๋?
์๊ฐ๋ณต์ก๋(Time Complexity)๋ ์๊ณ ๋ฆฌ์ฆ์ด ์ ๋ ฅ ํฌ๊ธฐ์ ๋ฐ๋ผ ์คํ ์๊ฐ์ด ์ด๋ป๊ฒ ์ฆ๊ฐํ๋์ง๋ฅผ ๋ํ๋ด๋ ์งํ์ ๋๋ค.
- O(1): ์์ ์๊ฐ - ์ ๋ ฅ ํฌ๊ธฐ์ ๋ฌด๊ดํ๊ฒ ์ผ์ ํ ์๊ฐ
- O(n): ์ ํ ์๊ฐ - ์ ๋ ฅ ํฌ๊ธฐ์ ๋น๋กํ์ฌ ์๊ฐ ์ฆ๊ฐ
- O(n²): ์ ๊ณฑ ์๊ฐ - ์ ๋ ฅ ํฌ๊ธฐ์ ์ ๊ณฑ์ ๋น๋กํ์ฌ ์๊ฐ ์ฆ๊ฐ
- O(log n): ๋ก๊ทธ ์๊ฐ - ์ ๋ ฅ ํฌ๊ธฐ๊ฐ ์ฆ๊ฐํด๋ ์ฒ์ฒํ ์๊ฐ ์ฆ๊ฐ
๐ ์ฑ๋ฅ ๋น๊ต ์ฐจํธ
๐ป ์ฝ๋ ๋น๊ต
O(n)
โ ํจ์จ์ ์ธ ๋ฐฉ๋ฒ (ํ์ฌ ์ฝ๋)
const qaGroups = qaResponses.reduce((groups, response) => {
const { timestamp, question } = response;
if (!groups[timestamp]) { // O(1) ์ ๊ทผ
groups[timestamp] = {
timestamp,
question,
responses: [],
};
}
groups[timestamp].responses.push(response);
return groups;
}, {});
// O(g log g) - g๋ ๊ทธ๋ฃน ์
const sortedQAGroups = Object.values(qaGroups)
.sort((a, b) => a.timestamp - b.timestamp);
O(n²)
โ ๋นํจ์จ์ ์ธ ๋ฐฉ๋ฒ
const qaGroups = qaResponses.reduce((groups, response) => {
// O(g) - ๋งค๋ฒ ๋ฐฐ์ด์ ์ํํด์ ์ฐพ๊ธฐ
const existingGroup = groups.find(g =>
g.timestamp === response.timestamp
);
if (existingGroup) {
existingGroup.responses.push(response);
} else {
groups.push({
timestamp: response.timestamp,
question: response.question,
responses: [response]
});
}
return groups;
}, []);
๐ ํต์ฌ ์ฐจ์ด์
๊ฐ์ฒด์ ํค ์ ๊ทผ์ O(1) ์๊ฐ์ ๊ฐ๋ฅํ์ง๋ง, ๋ฐฐ์ด์์ ํน์ ์กฐ๊ฑด์ ์์ ์ฐพ๊ธฐ๋ O(n) ์๊ฐ์ด ํ์ํฉ๋๋ค!
๐ ์ฑ๋ฅ ๋ถ์
์๋ต 100๊ฐ, ๊ทธ๋ฃน 10๊ฐ
110 vs 5,050
์ฐ์ฐ ํ์ ๋น๊ต
์๋ต 1,000๊ฐ, ๊ทธ๋ฃน 50๊ฐ
1,087 vs 500,500
์ฐ์ฐ ํ์ ๋น๊ต
์ฑ๋ฅ ํฅ์
460๋ฐฐ
๋ ๋น ๋ฅธ ์ฒ๋ฆฌ ์๋
๐ ์์ธ ์ฑ๋ฅ ๋น๊ตํ
| ์๋ต ์ (n) | ๊ทธ๋ฃน ์ (g) | ํจ์จ์ ๋ฐฉ๋ฒ O(n + g log g) | ๋นํจ์จ์ ๋ฐฉ๋ฒ O(n²) | ์ฑ๋ฅ ์ฐจ์ด |
|---|---|---|---|---|
| 100 | 10 | 110 | 5,050 | 46๋ฐฐ ๋น ๋ฆ |
| 500 | 25 | 625 | 125,250 | 200๋ฐฐ ๋น ๋ฆ |
| 1,000 | 50 | 1,087 | 500,500 | 460๋ฐฐ ๋น ๋ฆ |
| 5,000 | 100 | 5,200 | 12,502,500 | 2,404๋ฐฐ ๋น ๋ฆ |
๐ฏ ์ reduce๋ฅผ ์ฌ์ฉํด์ ๊ฐ์ฒด๋ก ๊ทธ๋ฃนํํ๋๊ฐ?
- ํด์ ํ ์ด๋ธ์ ํ์ฉ: JavaScript ๊ฐ์ฒด๋ ํด์ ํ ์ด๋ธ๋ก ๊ตฌํ๋์ด ํค ์ ๊ทผ์ด O(1)
- ์ค๋ณต ๊ฒ์ ์ ๊ฑฐ: ๊ฐ์ ํ์์คํฌํ๋ฅผ ๊ฐ์ง ๊ทธ๋ฃน์ ์ฐพ๊ธฐ ์ํด ๋งค๋ฒ ๋ฐฐ์ด์ ์ํํ ํ์ ์์
- ๋ฉ๋ชจ๋ฆฌ ํจ์จ์ฑ: ๊ฐ ํ์์คํฌํ๋ง๋ค ํ๋์ ๊ทธ๋ฃน๋ง ์์ฑ
- ํ์ฅ์ฑ: ๋ฐ์ดํฐ๊ฐ ๋ง์์ ธ๋ ์ฑ๋ฅ ์ ํ๊ฐ ์๋งํจ
โก ์ฑ๋ฅ ์ต์ ํ ํฌ์ธํธ
- ๊ทธ๋ฃนํ ๋จ๊ณ: reduce + ๊ฐ์ฒด ํค ์ ๊ทผ์ผ๋ก O(n) ์๊ฐ์ ์๋ฃ
- ์ ๋ ฌ ๋จ๊ณ: Object.values()๋ก ๋ฐฐ์ด ๋ณํ ํ ๊ทธ๋ฃน ์๋งํผ๋ง ์ ๋ ฌ (O(g log g))
- ์ ์ฒด ๋ณต์ก๋: O(n + g log g) ≈ O(n) (์ผ๋ฐ์ ์ผ๋ก g << n)
๐ ์คํ ์๊ฐ ๋น๊ต ๊ทธ๋ํ