Problem description:

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.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

Example 1:

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

Example 2:

1
2
3
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.

Example 3:

1
2
3
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 (More info).

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • order.length == 26
  • All characters in words[i] and order are English lowercase letters.

Solution:

Build a transform mapping from order,Find all alien words with letters in normal order.

For example, if we have order = "xyz..."We can map the word "xyz" to "abc" or "123"

Then we check if all words are in sorted order.

For example,words = [“hello”,”leetcode”]order = “hlabcdefgijkmnopqrstuvwxyz”

  1. Create a dic, key is each word in new order, value is its index, which means its new position in the new order.
  2. Transform the list of words into its index in new order.words = ["hello","leetcode"] -> [[0, 6, 1, 1, 14], [1, 6, 6, 19, 4, 14, 5, 6]]
  3. zip() will zip 2 element one by one,zip(words, words[1:]) here will combine first element(words[0]) in words with words[1], so we can compare current element with next element: word[0]->word[1], word[1]->word[2]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
dic = {c: i for i, c in enumerate(order)}
new_words = []

for w in words:
new = []
for c in w:
new.append(dic[c])
new_words.append(new)
for w1, w2 in zip(new_words, new_words[1:]):
if w1 > w2:
return False
return True

time complexity: $O(NS)$, N words, length = S
space complexity: $O(1)$
reference:
related problem: