Find order Of Characters From Alien Dictionary Problem

Hello!

What Is an Alien Dictionary?
An alien dictionary is simply a collection of words written in an unknown language. The words appear jumbled because the underlying character order is not yet known. The task is to reconstruct the correct order of characters so that the words are sorted lexicographically according to the rules of that language.

What Are “Characters” in This Context?
Characters are the individual letters that form the words of the alien dictionary. Consider the following example input:
Words: “cad”, “cab”, “abca”, “acbd”, “baa”

How to Find the Order of Characters
Two reliable approaches exist for solving this problem. Both treat the relationships between characters as a directed graph and then produce a valid ordering.
Method 1: Topological Sorting
Build a directed graph in which each node represents a unique character. For every pair of adjacent words, compare characters from left to right until the first mismatch is found; the character in the first word must precede the character in the second word, so an edge is added accordingly. After processing all pairs, perform a topological sort on the graph. The resulting sequence is the required character order.

Time Complexity: O(n + α), where n is the number of words and α is the number of unique characters.
Method 2: Comparing Adjacent Words Directly
Iterate through every pair of consecutive words. For each pair, scan the characters until the first mismatch appears and record the precedence relationship. Repeat until all pairs have been examined. The collected relationships can then be used to produce the final ordering, for example by feeding them into a graph-based sort or by maintaining a custom comparator in C++.

Time Complexity: O(N × L), where N is the number of words and L is the maximum word length.
Wrapping Up
Reconstructing the hidden order of an alien dictionary demonstrates how classic graph algorithms such as topological sorting can elegantly solve ordering problems. The same principles underpin many real-world tasks that involve dependency resolution and custom sort orders.
Thank you!
Join us on social media!
See you!
Subscribe to our newsletter
Get the latest Web3, AI, and crypto news delivered straight to your inbox.