LeetCode 0269. Alien Dictionary Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0269. Alien Dictionary

Description

There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.

You are given a list of strings words from the alien language's dictionary. Now it is claimed that the strings in words are sorted lexicographically by the rules of this new language.

If this claim is incorrect, and the given arrangement of string in words cannot correspond to any order of letters, return "".

Otherwise, return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there are multiple solutions, return any of them.

 

Example 1:

Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"

Example 2:

Input: words = ["z","x"]
Output: "zx"

Example 3:

Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of only lowercase English letters.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def alienOrder(self, words: List[str]) -> str: g = [[False] * 26 for _ in range(26)] s = [False] * 26 cnt = 0 n = len(words) for i in range(n - 1): for c in words[i]: if cnt == 26: break o = ord(c) - ord('a') if not s[o]: cnt += 1 s[o] = True m = len(words[i]) for j in range(m): if j >= len(words[i + 1]): return '' c1, c2 = words[i][j], words[i + 1][j] if c1 == c2: continue o1, o2 = ord(c1) - ord('a'), ord(c2) - ord('a') if g[o2][o1]: return '' g[o1][o2] = True break for c in words[n - 1]: if cnt == 26: break o = ord(c) - ord('a') if not s[o]: cnt += 1 s[o] = True indegree = [0] * 26 for i in range(26): for j in range(26): if i != j and s[i] and s[j] and g[i][j]: indegree[j] += 1 q = deque() ans = [] for i in range(26): if s[i] and indegree[i] == 0: q.append(i) while q: t = q.popleft() ans.append(chr(t + ord('a'))) for i in range(26): if s[i] and i != t and g[t][i]: indegree[i] -= 1 if indegree[i] == 0: q.append(i) return '' if len(ans) < cnt else ''.join(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !