Leetcode 953. Verifying an Alien Dictionary
Explanation for Leetcode 953 - Verifying an Alien Dictionary, and its solution in Python.
Problem
Leetcode 953 - Verifying an Alien Dictionary
Example:
1
2
3
4
5
6
7
8
9
10
11
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character
Approach
We can check every word and its adjacent to it if the order index is in the correct way.
if word1[i] != word2[i], then we can compare the order index and if word1[i]’s order index is bigger, then we can return False
Here is the Python code for the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
order_index = {c: i for i,c in enumerate(order)}
for i in range(len(words)-1):
w1, w2 = words[i], words[i+1]
for j in range(len(w1)):
if j == len(w2):
return False
if w1[j] != w2[j]:
if order_index[w1[j]] > order_index[w2[j]]:
return False
break
return True
Time Complexity and Space Complexity
Time Complexity: $O(n * m)$
Space Complexity: $O(1)$
This post is licensed under CC BY 4.0 by the author.