Verifying an Alien Dictionary — LeetCode 953 Python Solution
- Problem
- #953
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
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
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 TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.