Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Alien Dictionary Order

Hard · Graphs · Asked at Google, Amazon, Meta, Airbnb, Uber

An alien language uses lowercase English letters in an unknown order. You get a list of words that is claimed to be sorted in that language. Work out an order of all letters that appear in the words, consistent with the list.

Many orders can be consistent, so print the one that is smallest in normal alphabetical order (compare the orders as strings). If no order is consistent, print -1.

Input

First line: n. Next n lines: one word each.

Output

The letter order as one string, or -1.

Constraints

Compare each pair of neighbouring words: the first position where they differ gives an edge "letter a comes before letter b". If a word is followed by its own proper prefix, the list cannot be sorted (−1). Then run Kahn’s topological sort, always taking the smallest available letter (a min-heap) — a cycle means −1.

Example 1

Input

5
wrt
wrf
er
ett
rftt

Output

wertf

Example 2

Input

3
z
x
z

Output

-1

Hints

  1. Two neighbouring words tell you one fact: at their first differing position, the first word’s letter comes earlier.
  2. If a longer word comes before its own prefix ("abc" then "ab"), no order works.
  3. The facts form a directed graph on letters; you need a topological order — the smallest one alphabetically.

Approach

For every neighbouring pair, find the first differing position and add the edge a → b (ignore duplicates); if there is none and the first word is longer, print −1. Then run Kahn's algorithm over the letters that appear, always removing the alphabetically smallest letter with in-degree 0 (a min-heap, or a scan over 26 letters). If fewer letters come out than appear, there is a cycle — print −1.

Complexity: O(total letters + 26²) time · O(26²) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<string> w(n);
    for (auto &s : w) cin >> s;
    bool present[26] = {false}, edge[26][26] = {{false}};
    for (auto &s : w)
        for (char c : s) present[c - 'a'] = true;
    for (int i = 0; i + 1 < n; i++) {
        const string &a = w[i], &b = w[i + 1];
        size_t k = 0;
        while (k < a.size() && k < b.size() && a[k] == b[k]) k++;
        if (k == min(a.size(), b.size())) {
            if (a.size() > b.size()) {
                cout << -1 << "\n";
                return 0;
            }
            continue;
        }
        edge[a[k] - 'a'][b[k] - 'a'] = true;
    }
    int indeg[26] = {0}, total = 0;
    for (int u = 0; u < 26; u++)
        for (int v = 0; v < 26; v++) indeg[v] += edge[u][v];
    for (int c = 0; c < 26; c++) total += present[c];
    bool done[26] = {false};
    string order;
    while (true) {
        int u = -1;
        for (int c = 0; c < 26; c++)
            if (present[c] && !done[c] && indeg[c] == 0) {
                u = c;
                break;
            }
        if (u < 0) break;
        done[u] = true;
        order += char('a' + u);
        for (int v = 0; v < 26; v++)
            if (edge[u][v]) indeg[v]--;
    }
    cout << ((int) order.size() == total ? order : "-1") << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
w = data[1 : 1 + n]
present = set("".join(w))
edges = [set() for _ in range(26)]
bad = False
for a, b in zip(w, w[1:]):
    k = 0
    while k < len(a) and k < len(b) and a[k] == b[k]:
        k += 1
    if k == min(len(a), len(b)):
        if len(a) > len(b):
            bad = True
            break
        continue
    edges[ord(a[k]) - 97].add(ord(b[k]) - 97)
if bad:
    print(-1)
else:
    indeg = [0] * 26
    for u in range(26):
        for v in edges[u]:
            indeg[v] += 1
    letters = sorted(ord(c) - 97 for c in present)
    done = set()
    order = []
    while True:
        u = next((c for c in letters if c not in done and indeg[c] == 0), None)
        if u is None:
            break
        done.add(u)
        order.append(chr(97 + u))
        for v in edges[u]:
            indeg[v] -= 1
    print("".join(order) if len(order) == len(present) else -1)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] w = new String[n];
        for (int i = 0; i < n; i++) w[i] = br.readLine().trim();
        boolean[] present = new boolean[26];
        boolean[][] edge = new boolean[26][26];
        for (String s : w)
            for (char c : s.toCharArray()) present[c - 'a'] = true;
        for (int i = 0; i + 1 < n; i++) {
            String a = w[i], b = w[i + 1];
            int k = 0;
            while (k < a.length() && k < b.length() && a.charAt(k) == b.charAt(k)) k++;
            if (k == Math.min(a.length(), b.length())) {
                if (a.length() > b.length()) {
                    System.out.println(-1);
                    return;
                }
                continue;
            }
            edge[a.charAt(k) - 'a'][b.charAt(k) - 'a'] = true;
        }
        int[] indeg = new int[26];
        int total = 0;
        for (int u = 0; u < 26; u++)
            for (int v = 0; v < 26; v++) if (edge[u][v]) indeg[v]++;
        for (int c = 0; c < 26; c++) if (present[c]) total++;
        boolean[] done = new boolean[26];
        StringBuilder order = new StringBuilder();
        while (true) {
            int u = -1;
            for (int c = 0; c < 26; c++)
                if (present[c] && !done[c] && indeg[c] == 0) {
                    u = c;
                    break;
                }
            if (u < 0) break;
            done[u] = true;
            order.append((char) ('a' + u));
            for (int v = 0; v < 26; v++) if (edge[u][v]) indeg[v]--;
        }
        System.out.println(order.length() == total ? order.toString() : "-1");
    }
}

Solve Alien Dictionary Order online · All practice problems