File: verifying-an-alien-dictionary/solution.py

Date: 2026-06-06

Time: 19:41

verifying-an-alien-dictionary/solution.py

Purpose

This file solves LeetCode 953: Verifying an Alien Dictionary. Given a list of words and a string defining a custom alphabet ordering, it determines whether the words are sorted lexicographically according to that alien alphabet. It's one of ~500 solutions in the leetcode-implementations repo, each in its own directory.

Note: the function is misnamed reverse_string — it has nothing to do with reversing strings. The signature and docstring correctly describe alien dictionary verification.

Key Components

reverse_string(words, order) -> bool — the sole public function. Despite the name, it checks whether words is sorted under the alphabet defined by order.

Patterns

Rank-mapping idiom: Building a {char: index} dict from the ordering string is the standard approach for custom-alphabet problems. It turns O(n) alphabet lookups into O(1) dict lookups.

Early-exit comparison: The inner loop mirrors how strcmp works — it walks characters in lockstep and returns as soon as it finds a decisive difference. Three cases at each character position:

1. rank[w1[j]] < rank[w2[j]] → w1 comes first, break (this pair is fine, move to next pair)

2. rank[w1[j]] > rank[w2[j]] → w1 comes after w2, return False

3. Equal → continue to next character

Flow

1. Build rank lookup from order.

2. For each consecutive pair (w1, w2):

3. If all pairs pass, return True.

Dependencies

Imports: Only typing.List — no external dependencies.

Imported by: The test_solution.py in the same directory. The "Imported By" list in the prompt is misleading — those hundreds of test files each import their *own* solution.py, not this one.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints. Characters not in order will produce an unhandled KeyError. Empty words list returns True (the loop body never executes).