SDE & MLE Prep

953. Verifying an Alien Dictionary

Problem

An alien language uses the lowercase letters in a different order, given as the string order. Decide whether words is sorted lexicographically in that alphabet (a word sorts before any longer word it is a prefix of).

Example: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" → true

Map each letter to its rank; compare adjacent words at their first differing character. If none differ, the shorter word must come first.

Complexity: O(total characters).

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        rank = {ch: i for i, ch in enumerate(order)}
        keys = [[rank[ch] for ch in w] for w in words]
        return all(a <= b for a, b in zip(keys, keys[1:]))   # list comparison = lexicographic