KatInterview

269. Alien Dictionary

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find a valid alphabetical order of letters from a new alien language. We are given a list of words, which are sorted lexicographically according to this new language's rules. This problem can be modeled as finding a topological sort of a directed graph.

Solution

Alien Dictionary in Python

from collections import defaultdict, deque

class Solution:
    def alienOrder(self, words: list[str]) -> str:
        # Step 1: Initialize data structures
        adj = defaultdict(set)
        in_degree = defaultdict(int)

        # Find all unique characters
        all_chars = set("".join(words))
        for char in all_chars:
            in_degree[char] = 0

        # Step 2: Build the graph
        for i in range(len(words) - 1):
            word1, word2 = words[i], words[i + 1]
            min_len = min(len(word1), len(word2))

            # Check for invalid case like ["abc", "ab"]
            if len(word1) > len(word2) and word1.startswith(word2):
                return ""

            # Find the first differing character to establish an edge
            for j in range(min_len):
                if word1[j] != word2[j]:
                    u, v = word1[j], word2[j]
                    # Add edge u -> v if it's not already there
                    if v not in adj[u]:
                        adj[u].add(v)
                        in_degree[v] += 1
                    break # First difference is enough
        
        # Step 3: Topological sort (Kahn's algorithm)
        queue = deque([char for char in all_chars if in_degree[char] == 0])
        result = []

        while queue:
            u = queue.popleft()
            result.append(u)

            for v in adj[u]:
                in_degree[v] -= 1
                if in_degree[v] == 0:
                    queue.append(v)

        # Step 4: Check for cycle
        if len(result) == len(all_chars):
            return "".join(result)
        else:
            return ""

Alien Dictionary in Java

class Solution {
    public String alienOrder(String[] words) {
        if (words == null || words.length == 0) {
            return "";
        }

        // Step 1: Create data structures and find all unique letters.
        Map<Character, Set<Character>> adj = new HashMap<>();
        Map<Character, Integer> inDegree = new HashMap<>();
        for (String word : words) {
            for (char c : word.toCharArray()) {
                inDegree.put(c, 0);
                adj.put(c, new HashSet<>());
            }
        }

        // Step 2: Build the graph by comparing adjacent words.
        for (int i = 0; i < words.length - 1; i++) {
            String word1 = words[i];
            String word2 = words[i + 1];
            int len = Math.min(word1.length(), word2.length());

            // Check for invalid case like ["abc", "ab"]
            if (word1.length() > word2.length() && word1.startsWith(word2)) {
                return "";
            }

            for (int j = 0; j < len; j++) {
                char u = word1.charAt(j);
                char v = word2.charAt(j);
                if (u != v) {
                    // Add edge u -> v
                    if (!adj.get(u).contains(v)) {
                        adj.get(u).add(v);
                        inDegree.put(v, inDegree.get(v) + 1);
                    }
                    break; // Only the first different character matters
                }
            }
        }

        // Step 3: Topological sort (Kahn's algorithm)
        Queue<Character> queue = new LinkedList<>();
        for (char c : inDegree.keySet()) {
            if (inDegree.get(c) == 0) {
                queue.offer(c);
            }
        }

        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()) {
            char u = queue.poll();
            sb.append(u);

            for (char v : adj.get(u)) {
                inDegree.put(v, inDegree.get(v) - 1);
                if (inDegree.get(v) == 0) {
                    queue.offer(v);
                }
            }
        }

        // Step 4: Check if a valid order was found
        if (sb.length() == inDegree.size()) {
            return sb.toString();
        } else {
            // Graph has a cycle
            return "";
        }
    }
}

Alien Dictionary in C++

class Solution {
public:
    string alienOrder(vector<string>& words) {
        if (words.empty()) {
            return "";
        }

        unordered_map<char, unordered_set<char>> adj;
        unordered_map<char, int> in_degree;

        // Initialize the graph nodes (all unique characters)
        for (const string& word : words) {
            for (char c : word) {
                in_degree[c] = 0;
            }
        }

        // Build the graph by comparing adjacent words
        for (int i = 0; i < words.size() - 1; ++i) {
            string word1 = words[i];
            string word2 = words[i+1];
            int len = min(word1.length(), word2.length());

            // Check for invalid case like ["abc", "ab"]
            if (word1.length() > word2.length() && word1.rfind(word2, 0) == 0) {
                return "";
            }

            for (int j = 0; j < len; ++j) {
                if (word1[j] != word2[j]) {
                    char u = word1[j];
                    char v = word2[j];
                    // Add edge u -> v if it doesn't exist yet
                    if (adj[u].find(v) == adj[u].end()) {
                        adj[u].insert(v);
                        in_degree[v]++;
                    }
                    break; // Only the first differing character matters
                }
            }
        }

        // Topological Sort (Kahn's Algorithm)
        queue<char> q;
        for (auto const& [key, val] : in_degree) {
            if (val == 0) {
                q.push(key);
            }
        }

        string result = "";
        while (!q.empty()) {
            char u = q.front();
            q.pop();
            result += u;

            if (adj.count(u)) {
                for (char v : adj[u]) {
                    in_degree[v]--;
                    if (in_degree[v] == 0) {
                        q.push(v);
                    }
                }
            }
        }

        // If result's length is not equal to the number of unique characters,
        // there is a cycle in the graph.
        if (result.length() == in_degree.size()) {
            return result;
        } else {
            return "";
        }
    }
};

Alien Dictionary in TypeScript

function alienOrder(words: string[]): string {
    if (!words || words.length === 0) {
        return "";
    }

    // Step 1: Create data structures and find all unique letters.
    const adj = new Map<string, Set<string>>();
    const inDegree = new Map<string, number>();

    for (const word of words) {
        for (const char of word) {
            if (!inDegree.has(char)) {
                inDegree.set(char, 0);
                adj.set(char, new Set());
            }
        }
    }

    // Step 2: Build the graph by comparing adjacent words.
    for (let i = 0; i < words.length - 1; i++) {
        const word1 = words[i];
        const word2 = words[i + 1];
        const len = Math.min(word1.length, word2.length);

        // Check for invalid case like ["abc", "ab"]
        if (word1.length > word2.length && word1.startsWith(word2)) {
            return "";
        }

        for (let j = 0; j < len; j++) {
            const u = word1[j];
            const v = word2[j];
            if (u !== v) {
                // Add edge u -> v
                if (!adj.get(u)!.has(v)) {
                    adj.get(u)!.add(v);
                    inDegree.set(v, inDegree.get(v)! + 1);
                }
                break; // Only the first different character matters
            }
        }
    }

    // Step 3: Topological sort (Kahn's algorithm)
    const queue: string[] = [];
    for (const char of inDegree.keys()) {
        if (inDegree.get(char) === 0) {
            queue.push(char);
        }
    }

    let result = "";
    while (queue.length > 0) {
        const u = queue.shift()!;
        result += u;

        if (adj.has(u)) {
            for (const v of adj.get(u)!) {
                inDegree.set(v, inDegree.get(v)! - 1);
                if (inDegree.get(v) === 0) {
                    queue.push(v);
                }
            }
        }
    }

    // Step 4: Check if a valid order was found
    if (result.length === inDegree.size) {
        return result;
    } else {
        // Graph has a cycle
        return "";
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.