|
| 1 | +''' |
| 2 | +If a is a synonym of b and b is a synonym of c, this implies that a is a synonym of c and c is a synonym of a |
| 3 | + |
| 4 | +"advice:counsel counsel:suggestion suggestion:advice activity:briskness briskness:liveliness" |
| 5 | +briskness |
| 6 | +[liveliness, activity] |
| 7 | + |
| 8 | +In this example, advice, counsel, suggestion are all synonyms of each other, while advice is not a synonym of activity. |
| 9 | + |
| 10 | +Problem: Given an input data in the format above and a word, write a program to find out all the synonyms of that word. |
| 11 | + |
| 12 | + |
| 13 | +input: string of synonyms, word |
| 14 | +string |
| 15 | + input always valid |
| 16 | + no empty string |
| 17 | + always at least 1 pair of words |
| 18 | +word |
| 19 | + no empty string |
| 20 | + edge case: word not in synonym string |
| 21 | + |
| 22 | + |
| 23 | +Convert string of synonyms -> adjacency list -> Loop adjacency list -> DFS from each node if it matches input word. Append to result list. |
| 24 | +TC: O(N + M^2), N = Chars in string, M = Unique Words |
| 25 | +SC: O(M) |
| 26 | +''' |
| 27 | + |
| 28 | +from collections import defaultdict |
| 29 | + |
| 30 | +class Solution: |
| 31 | + def listSynonyms(self, pairs: str, word: str) -> list[str]: |
| 32 | + tokens = pairs.split(" ") |
| 33 | + |
| 34 | + adj = defaultdict(list) |
| 35 | + |
| 36 | + for t in tokens: |
| 37 | + n1, n2 = t.split(":") |
| 38 | + adj[n1].append(n2) |
| 39 | + adj[n2].append(n1) |
| 40 | + |
| 41 | + def dfs(node): |
| 42 | + if node in visited: |
| 43 | + return |
| 44 | + res.append(node) |
| 45 | + visited.add(node) |
| 46 | + for neighbor in adj[node]: |
| 47 | + dfs(neighbor) |
| 48 | + |
| 49 | + res = [] |
| 50 | + visited = set() |
| 51 | + |
| 52 | + for root in adj.keys(): |
| 53 | + if root == word: |
| 54 | + dfs(root) |
| 55 | + |
| 56 | + return res[1:] if res else res |
| 57 | + |
| 58 | + |
| 59 | +solution = Solution() |
| 60 | +print(solution.listSynonyms("advice:counsel counsel:suggestion suggestion:advice activity:briskness briskness:liveliness", "briskness")) |
| 61 | +print(solution.listSynonyms("advice:counsel counsel:suggestion suggestion:advice activity:briskness briskness:liveliness", "rock")) |
| 62 | +print(solution.listSynonyms("advice:counsel counsel:suggestion suggestion:advice activity:briskness briskness:liveliness", "counsel")) |
| 63 | +print(solution.listSynonyms("advice:counsel", "rock")) |
| 64 | +print(solution.listSynonyms("advice:counsel", "counsel")) |
| 65 | +print(solution.listSynonyms("a:b b:c c:d d:e e:f", "f")) |
0 commit comments