You are given a sequence of words and an alien alphabet order, which is a permutation of the 26 lowercase English letters. Determine whether the words are sorted lexicographically according to this alien alphabet.
Function Signature
def is_alien_sorted(words: list[str], order: str) -> bool:
Rules
-
Letter
x
comes before letter
y
when
x
appears earlier in
order
.
-
To compare two words, find the first position where they differ. The word whose letter comes earlier in
order
is the smaller word.
-
If one word is a prefix of the other, the shorter word is the smaller one. For example,
"app"
must come before
"apple"
.
-
The list counts as sorted when every word is less than or equal to the word after it, so equal adjacent words are allowed.
-
Return
True
if the list is sorted and
False
otherwise.
Constraints
-
1 <= len(words) <= 100
-
1 <= len(words[i]) <= 20
-
len(order) == 26
-
All characters in
words[i]
and
order
are lowercase English letters
-
order
contains every lowercase English letter exactly once
Examples
Input: words = ["hello", "lantern"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: True
The words first differ at position 0, where h meets l. In this alphabet h comes before l, so the pair is in order.
Input: words = ["word", "world", "row"], order = "worldabcefghijkmnpqstuvxyz"
Output: False
"word" and "world" share wor and then differ at d versus l. In this alphabet l comes before d, so "world" should come first and the list is not sorted.
Input: words = ["apple", "app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: False
All three letters of "app" match the start of "apple", so the shorter word "app" must come first.