EasyNo. 0953

Verifying an Alien Dictionary — LeetCode 953 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.