Algo-Sim › Advanced Graphs
Alien Dictionary
Hard · Advanced Graphs · step through it in Java, Python and C++ on your own input
Given words sorted in an unknown alphabet, return a valid letter order (or "" if none). Compare neighbours for rules, then topologically sort.
Problem
An alien language uses lowercase English letters in an unknown order. Given its words already sorted in that order, return a string of all the letters they use in a valid alphabet order, or "" if the list contradicts itself. Any valid order is accepted.
Constraints
- 1 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 100
- Words contain only lowercase letters
- A word followed by its own proper prefix is a contradiction
Edge cases to test
- A word followed by its own prefix: invalid (
"") - One word: its letters in any order
- Letters that appear but are never compared
Follow-up questions
- Why compare only adjacent words?
- Sorted order means each adjacent pair gives at most one rule; other pairs follow from those rules by transitivity.
- What is the cost?
- O(C) for C total characters to build the rules, plus a topological sort over at most 26 letters.
Solution
Java
public String alienOrder(String[] words) {
Map<Character, List<Character>> adj = new LinkedHashMap<>();
Map<Character, Integer> indegree = new LinkedHashMap<>();
for (String w : words) {
for (char c : w.toCharArray()) {
adj.putIfAbsent(c, new ArrayList<>());
indegree.putIfAbsent(c, 0);
}
}
for (int i = 0; i + 1 < words.length; i++) {
String a = words[i], b = words[i + 1];
if (a.length() > b.length() && a.startsWith(b)) return "";
for (int j = 0; j < Math.min(a.length(), b.length()); j++) {
char x = a.charAt(j), y = b.charAt(j);
if (x != y) {
if (!adj.get(x).contains(y)) {
adj.get(x).add(y);
indegree.merge(y, 1, Integer::sum);
}
break;
}
}
}
Queue<Character> queue = new ArrayDeque<>();
for (char c : indegree.keySet()) {
if (indegree.get(c) == 0) queue.offer(c);
}
StringBuilder order = new StringBuilder();
while (!queue.isEmpty()) {
char c = queue.poll();
order.append(c);
for (char next : adj.get(c)) {
if (indegree.merge(next, -1, Integer::sum) == 0) queue.offer(next);
}
}
return order.length() == indegree.size() ? order.toString() : "";
}Python
from collections import deque
def alien_order(words):
adj, indegree = {}, {}
for w in words:
for c in w:
adj.setdefault(c, [])
indegree.setdefault(c, 0)
for a, b in zip(words, words[1:]):
if len(a) > len(b) and a.startswith(b):
return ""
for x, y in zip(a, b):
if x != y:
if y not in adj[x]:
adj[x].append(y)
indegree[y] += 1
break
queue = deque(c for c in indegree if indegree[c] == 0)
order = []
while queue:
c = queue.popleft()
order.append(c)
for nxt in adj[c]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return "".join(order) if len(order) == len(indegree) else ""C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string alienOrder(vector<string> &words) {
unordered_map<char, vector<char>> adj;
unordered_map<char, int> indegree;
vector<char> letters;
for (const string &w : words) {
for (char c : w) {
if (!indegree.count(c)) {
indegree[c] = 0;
letters.push_back(c);
}
}
}
for (int i = 0; i + 1 < int(words.size()); ++i) {
const string &a = words[i];
const string &b = words[i + 1];
if (a.size() > b.size() && a.compare(0, b.size(), b) == 0)
return "";
for (int j = 0; j < int(min(a.size(), b.size())); ++j) {
char x = a[j], y = b[j];
if (x != y) {
if (find(adj[x].begin(), adj[x].end(), y) == adj[x].end()) {
adj[x].push_back(y);
++indegree[y];
}
break;
}
}
}
deque<char> queue;
for (char c : letters)
if (indegree[c] == 0)
queue.push_back(c);
string order;
while (!queue.empty()) {
char c = queue.front();
queue.pop_front();
order += c;
for (char next : adj[c])
if (--indegree[next] == 0)
queue.push_back(next);
}
return order.size() == indegree.size() ? order : "";
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)