Approach
Breadth-first search
For Alien Dictionary, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 57 lines of Java from the credited upstream file 269.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String alienOrder(String[] words) {3 Map<Character, Set<Character>> graph = new HashMap<>();4 int[] inDegrees = new int[26];5 buildGraph(graph, words, inDegrees);6 return topology(graph, inDegrees);7 }8 9 private void buildGraph(Map<Character, Set<Character>> graph, String[] words, int[] inDegrees) {10 11 for (final String word : words)12 for (final char c : word.toCharArray())13 graph.putIfAbsent(c, new HashSet<>());14 15 for (int i = 1; i < words.length; ++i) {16 final String first = words[i - 1];17 final String second = words[i];18 final int length = Math.min(first.length(), second.length());19 for (int j = 0; j < length; ++j) {20 final char u = first.charAt(j);21 final char v = second.charAt(j);22 if (u != v) {23 if (!graph.get(u).contains(v)) {24 graph.get(u).add(v);25 ++inDegrees[v - 'a'];26 }27 break; 28 }29 30 if (j == length - 1 && first.length() > second.length()) {31 graph.clear();32 return;33 }34 }35 }36 }37 38 private String topology(Map<Character, Set<Character>> graph, int[] inDegrees) {39 StringBuilder sb = new StringBuilder();40 Queue<Character> q = graph.keySet()41 .stream()42 .filter(c -> inDegrees[c - 'a'] == 0)43 .collect(Collectors.toCollection(ArrayDeque::new));44 45 while (!q.isEmpty()) {46 final char u = q.poll();47 sb.append(u);48 for (final char v : graph.get(u))49 if (--inDegrees[v - 'a'] == 0)50 q.offer(v);51 }52 53 54 return sb.length() == graph.size() ? sb.toString() : "";55 }56}57