Verifying an Alien Dictionary (LeetCode 953): Solution and Explanation

Easy
Array
Hash Table
String

An alien language uses the 26 lowercase letters in a different order, given as the string order. Return true if the list words is sorted the way a dictionary in that language would sort it, where the first differing letter decides and a prefix comes before any longer word that starts with it.

Intuition

Sorting is a property of neighbours. If every word is no greater than the word right after it, the whole list is sorted, because the relation chains along. So instead of comparing every pair of words you only need to check words[k] against words[k + 1], which is n - 1 comparisons.

Comparing two words in a dictionary works the same in any alphabet: line them up, skip the columns where the letters match, and look at the first column where they differ. That one column decides the order, and nothing to its right matters. The only thing that changes in the alien version is how you compare two letters.

To compare letters quickly, turn order into a rank table where rank[c] is the position of c in the alien alphabet. Then the left word is bigger exactly when rank[a[j]] > rank[b[j]] at the first differing column j.

One case has no differing column at all: one word is a prefix of the other. There the shorter word must come first, so "app" before "apple" is fine but "apple" before "app" is not. Forgetting this case is the most common bug.

Approach: Rank table and adjacent pairs

  1. Build rank so that rank[order[i]] = i for every i.
  2. For each k from 0 to len(words) - 2, take a = words[k] and b = words[k + 1] and let n = min(len(a), len(b)).
  3. Advance j from 0 while j < n and a[j] == b[j].
  4. If j == n, the shorter word is a prefix of the other. Return false when len(a) > len(b).
  5. Otherwise return false when rank[a[j]] > rank[b[j]].
  6. If every pair passes, return true.

Step-by-step example

words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
  1. Build the rank table: 'h' is 0, 'l' is 1, 'a' is 2, and so on through the order string.
  2. There is one pair to check: "hello" and "leetcode", with n = min(5, 8) = 5.
  3. Column 0 already differs: 'h' against 'l'.
  4. rank['h'] = 0 is less than rank['l'] = 1, so "hello" correctly comes first. The rest of the letters are not looked at.
  5. No pair failed, so the function returns true.

Code: Python, Java, C++

1class Solution:
2    def isAlienSorted(self, words: List[str], order: str) -> bool:
3        rank = {c: i for i, c in enumerate(order)}
4        for k in range(len(words) - 1):
5            a, b = words[k], words[k + 1]
6            n = min(len(a), len(b))
7            j = 0
8            while j < n and a[j] == b[j]:
9                j += 1
10            if j == n:
11                if len(a) > len(b):
12                    return False
13            elif rank[a[j]] > rank[b[j]]:
14                return False
15        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Rank table and adjacent pairs O(C)
Translate and compare O(C)
Sort with a custom key and compare O(C log n)
Time

O(C)

C is the total number of characters across all words. Each pair scan stops at the first difference, so each character is read at most twice, once in each pair it belongs to. Building the rank table is a constant 26 steps.

Space

O(1)

The rank table always has 26 entries, and the pair check uses a few index variables.

Other approaches

Translate and compare (time O(C), space O(C))

Map every letter of every word to the English letter with the same rank (alien 'h' becomes 'a', and so on), then check that the translated list is sorted with the normal string comparison. It is short and correct, but it builds a copy of every word.

Sort with a custom key and compare (time O(C log n), space O(C))

Sort a copy of the list using the rank sequence of each word as the key and check whether it equals the original. It works, but sorting costs O(C log n) when one linear pass is enough.

Common mistakes

  • Ignoring the prefix case. When the shorter length runs out without a difference, "apple" before "app" must return false.
  • Continuing past the first differing column. Once a[j] and b[j] differ, that column alone decides the pair, even if later letters look out of order.
  • Returning true as soon as one pair is in order. A single good pair says nothing about the others; only a bad pair lets you stop early.
  • Comparing letters with their normal character codes instead of their alien ranks.

Frequently asked questions

Why is it enough to compare only adjacent words?

Lexicographic order is transitive. If words[0] <= words[1] and words[1] <= words[2], then words[0] <= words[2], so checking neighbours covers every pair.

What happens when two words are identical?

The scan reaches the end without a difference and the lengths are equal, so the pair counts as in order. Duplicates do not break sortedness.

How is this different from Alien Dictionary (LeetCode 269)?

Here the alphabet is given and you only verify a list against it. In Alien Dictionary the alphabet is unknown and you rebuild it from a sorted list with a topological sort over letter constraints.

What is the time complexity of Verifying an Alien Dictionary?

O(C), where C is the total number of characters in words, with O(1) extra space for the 26-entry rank table.