Alien Dictionary — LeetCode 269 Python Solution

HardLeetCode PremiumDepth-First SearchBreadth-First SearchGraphTopological SortArrayString
Problem
#269
Reading time
9 min

The problem

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

Example

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

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 269. Alien Dictionary is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75 and NeetCode 150.

Frequently asked questions

How hard is LeetCode 269. Alien Dictionary?
LeetCode 269. Alien Dictionary is rated Hard on LeetCode.
What is the time complexity of LeetCode 269. Alien Dictionary?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 269. Alien Dictionary?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 269. Alien Dictionary cover?
LeetCode 269. Alien Dictionary is tagged Depth-First Search, Breadth-First Search, Graph, Topological Sort, Array and String on LeetCode.
Is LeetCode 269. Alien Dictionary a premium problem?
Yes. LeetCode 269. Alien Dictionary is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview