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
- 64 lines of C++ from the credited upstream file 269.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 7 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:3 string alienOrder(vector<string>& words) {4 unordered_map<char, unordered_set<char>> graph;5 vector<int> inDegrees(26);6 buildGraph(graph, words, inDegrees);7 return topology(graph, inDegrees);8 }9 10 private:11 void buildGraph(unordered_map<char, unordered_set<char>>& graph,12 const vector<string>& words, vector<int>& inDegrees) {13 14 for (const string& word : words)15 for (const char c : word)16 if (!graph.contains(c))17 graph[c] = unordered_set<char>();18 19 for (int i = 1; i < words.size(); ++i) {20 const string& first = words[i - 1];21 const string& second = words[i];22 const int length = min(first.length(), second.length());23 for (int j = 0; j < length; ++j) {24 const char u = first[j];25 const char v = second[j];26 if (u != v) {27 if (!graph[u].contains(v)) {28 graph[u].insert(v);29 ++inDegrees[v - 'a'];30 }31 break; 32 }33 34 if (j == length - 1 && first.length() > second.length()) {35 graph.clear();36 return;37 }38 }39 }40 }41 42 string topology(unordered_map<char, unordered_set<char>>& graph,43 vector<int>& inDegrees) {44 string s;45 queue<char> q;46 47 for (const auto& [c, _] : graph)48 if (inDegrees[c - 'a'] == 0)49 q.push(c);50 51 while (!q.empty()) {52 const char u = q.front();53 q.pop();54 s += u;55 for (const char v : graph[u])56 if (--inDegrees[v - 'a'] == 0)57 q.push(v);58 }59 60 61 return s.length() == graph.size() ? s : "";62 }63};64