LeetCode 269: Alien Dictionary Solution

Master LeetCode problem 269 (Alien Dictionary), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

The problem asks us to find the correct order of characters in an alien language based on a given list of words. We can model this problem as a graph where each character is a node and the relative order of characters in adjacent words gives us directed edges in the graph.

  1. Construct the graph: Iterate through the list of words to build the graph representation. Compare adjacent words to find the first differing character. Add an edge from the character in the first word to the character in the second word.
  2. Topological Sort: Perform topological sorting on the constructed graph to find the correct order of characters.
  3. Handle cyclic dependencies: If there is a cyclic dependency in the graph, it means the input is invalid as the order cannot be determined.

Time complexity: O(C), where C is the total length of all words in the input list. Space complexity: O(1) for the graph representation.

:

Solution Code

class Solution {
    public String alienOrder(String[] words) {
        Map<Character, List<Character>> graph = new HashMap<>();
        int[] indegree = new int[26];
        
        buildGraph(words, graph, indegree);
        
        return topologicalSort(graph, indegree);
    }
    
    private void buildGraph(String[] words, Map<Character, List<Character>> graph, int[] indegree) {
        for (String word : words) {
            for (char c : word.toCharArray()) {
                graph.putIfAbsent(c, new ArrayList<>());
            }
        }
        
        for (int i = 0; i < words.length - 1; i++) {
            String word1 = words[i];
            String word2 = words[i + 1];
            int minLength = Math.min(word1.length(), word2.length());
            
            for (int j = 0; j < minLength; j++) {
                char parent = word1.charAt(j);
                char child = word2.charAt(j);
                
                if (parent != child) {
                    graph.get(parent).add(child);
                    indegree[child - 'a']++;
                    break;
                }
                
                if (j == minLength - 1 && word1.length() > word2.length()) {
                    graph.clear(); // Invalid input, clear the graph
                    return;
                }
            }
        }
    }
    
    private String topologicalSort(Map<Character, List<Character>> graph, int[] indegree) {
        Queue<Character> queue = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        
        for (char c : graph.keySet()) {
            if (indegree[c - 'a'] == 0) {
                queue.offer(c);
            }
        }
        
        while (!queue.isEmpty()) {
            char curr = queue.poll();
            sb.append(curr);
            
            for (char neighbor : graph.get(curr)) {
                indegree[neighbor - 'a']--;
                if (indegree[neighbor - 'a'] == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        if (sb.length() < graph.size()) {
            return "";
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 269 (Alien Dictionary)?

This page provides optimized solutions for LeetCode problem 269 (Alien Dictionary) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 269 (Alien Dictionary)?

The time complexity for LeetCode 269 (Alien Dictionary) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 269 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 269 in Java, C++, or Python.

Back to LeetCode Solutions