Verifying an Alien Dictionary — LeetCode 953 Python Solution

EasyArrayHash TableString
Problem
#953
Pattern
Hash Map
Reading time
3 min

The problem

In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Example

Input
words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output
true
Explanation
As 'h' comes before 'l' in this language, then the sequence is sorted.

Python solution

Python
class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        m = {c: i for i, c in enumerate(order)}
        for i in range(20):
            prev = -1
            valid = True
            for x in words:
                curr = -1 if i >= len(x) else m[x[i]]
                if prev > curr:
                    return False
                if prev == curr:
                    valid = False
                prev = curr
            if valid:
                return True
        return True

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 953. Verifying an Alien Dictionary is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 953. Verifying an Alien Dictionary?
LeetCode 953. Verifying an Alien Dictionary is rated Easy on LeetCode.
What is the time complexity of LeetCode 953. Verifying an Alien Dictionary?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 953. Verifying an Alien Dictionary?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 953. Verifying an Alien Dictionary cover?
LeetCode 953. Verifying an Alien Dictionary is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview