|
| 1 | +# https://leetcode.com/problems/alien-dictionary/ |
| 2 | + |
| 3 | +from typing import List |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def alienOrder(self, words: List[str]) -> str: |
| 7 | + """ |
| 8 | + [Complexity] |
| 9 | + (V = words ๋ด unique ๋ฌธ์ ๊ฐ์, E = edge ๊ฐ์, L = words๋ด ๋ชจ๋ ๋ฌธ์ ๊ฐ์) |
| 10 | + - TC: O(V + L) (topo sort์ O(V + E) ์์ -> E < L ์ด๋ฏ๋ก) |
| 11 | + - SC: O(V + E) (graph) |
| 12 | +
|
| 13 | + [Approach] |
| 14 | + topo sort๋ฅผ ์ด์ฉํ์ฌ, words์ ํฌํจ๋ ์ ์ฒด ๋ฌธ์ ๊ฐ์์ topo sort ์์ผ๋ก ๋ฐฉ๋ฌธํ ๋ฌธ์ ๊ฐ์๋ฅผ ๋น๊ตํ์ฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค. |
| 15 | + 1) directed graph๋ฅผ ๊ตฌ์ฑํ ๋, words์์ ๋ ์ธ์ ํ ๋จ์ด๋ฅผ ๋น๊ตํ๋ฉฐ ์ฒซ ๋ฒ์งธ๋ก ๋ค๋ฅธ ๋ฌธ์๊ฐ ๋์ฌ ๋ graph & indegree๋ฅผ ๊ธฐ๋กํ๋ค. (sorted lexicographically) |
| 16 | + ์ด๋, ์์ resolving์ด ๋ถ๊ฐ๋ฅํ ๊ฒฝ์ฐ๋ฅผ ํ๋จํ์ฌ ๋น ๋ฅด๊ฒ ๋ฐํํ ์ ์๋ค. |
| 17 | + (์ธ์ ํ ๋ ๋จ์ด๋ฅผ ์์๋๋ก w1, w2๋ผ๊ณ ํ ๋, (1) w2๋ณด๋ค w1์ด ๋ ๊ธธ๋ฉด์ (2) w2๊ฐ w1์ ํฌํจ๋๋ ๊ฒฝ์ฐ, w1์ ๋๋จธ์ง ๋ถ๋ถ์ ์๋ ๋ฌธ์๋ ์์๋ฅผ ์ ์ ์๋ค.) |
| 18 | + 2) ์ด๋ ๊ฒ ๊ธฐ๋กํ graph & indegree๋ฅผ ๊ธฐ๋ฐ์ผ๋ก topo sort๋ก ๋ฐฉ๋ฌธํ ๋ฌธ์ ๊ฐ์์ ์ ์ฒด ๋ฌธ์ ๊ฐ์๋ฅผ ๋น๊ตํ์ฌ cycle์ด ๋ฐ์ํ์ง ์๋์ง ํ์ธํ๊ณ , |
| 19 | + cycle์ด ๋ฐ์ํ์ง ์์๋ค๋ฉด ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ, cycle์ด ๋ฐ์ํ๋ค๋ฉด ๋น ๋ฌธ์์ด์ ๋ฐํํ๋ค. |
| 20 | + """ |
| 21 | + from collections import defaultdict, deque |
| 22 | + |
| 23 | + # directed graph |
| 24 | + graph, indegree = {}, {} |
| 25 | + for word in words: |
| 26 | + for w in word: |
| 27 | + graph[w] = set() |
| 28 | + indegree[w] = 0 |
| 29 | + |
| 30 | + for i in range(len(words) - 1): |
| 31 | + w1, w2 = words[i], words[i + 1] |
| 32 | + # ๋ ์ธ์ ํ ๋จ์ด๋ฅผ ๋น๊ตํ๋ฉด์, ์ฒซ ๋ฒ์งธ๋ก ๋ค๋ฅธ ๋ฌธ์๊ฐ ๋์ฌ ๋ graph & indegree ๊ธฐ๋ก |
| 33 | + for j in range(min(len(w1), len(w2))): |
| 34 | + c1, c2 = w1[j], w2[j] |
| 35 | + # ์ฒซ ๋ฒ์งธ๋ก ๋ค๋ฅธ ๋ฌธ์ ๋ฐ๊ฒฌ ์, ๊ธฐ๋ก ํ ๋ค์ ๋จ์ด๋ก ๋์ด๊ฐ๊ธฐ |
| 36 | + if c1 != c2: |
| 37 | + if c2 not in graph[c1]: |
| 38 | + graph[c1].add(c2) |
| 39 | + indegree[c2] += 1 |
| 40 | + break |
| 41 | + # ์์๋ฅผ resolve ํ ์ ์๋ ๊ฒฝ์ฐ, ๋น ๋ฅด๊ฒ ๋ฆฌํด ***** |
| 42 | + # ex) words = ["abc", "ab"] (w1 = "abc", w2 = "ab") |
| 43 | + # -> (1) w2๋ณด๋ค w1์ด ๋ ๊ธธ๊ณ (2) w2๊ฐ w1์ ํฌํจ๋๋ค๋ฉด (=ํ์ฌ j๊ฐ w2์ ๋ง์ง๋ง ๋ฌธ์๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์๋ค๋ฉด) |
| 44 | + # w1[j + 1] ์ดํ์ ๋ฌธ์์ ๋ํด์๋ ์์๋ฅผ resolve ํ ์ ์์ |
| 45 | + elif len(w1) > len(w2) and j == min(len(w1), len(w2)) - 1: |
| 46 | + return "" |
| 47 | + |
| 48 | + # topo sort |
| 49 | + q = deque([w for w, ind in indegree.items() if ind == 0 and w in graph]) |
| 50 | + res = [] |
| 51 | + |
| 52 | + while q: |
| 53 | + w = q.popleft() |
| 54 | + res.append(w) |
| 55 | + |
| 56 | + for nw in graph[w]: |
| 57 | + indegree[nw] -= 1 |
| 58 | + if indegree[nw] == 0: |
| 59 | + q.append(nw) |
| 60 | + |
| 61 | + return "".join(res) if len(res) == len(graph) else "" |
0 commit comments