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 lexicographically in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
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:
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
Map the letters to the old order, and compare each pair.
Time complexity: o ( n ∗ m ) o(n*m) o(n∗m), where n
is the length of words, m
is the length of each word in words
Space complexity: o ( 1 ) o(1) o(1)
Code
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
def a_smaller_than_b(a: str, b: str) -> bool:
"""
Returns:
True: if a <= b
False: if a > b
"""
p1, p2 = 0, 0
while p1 < len(a) and p2 < len(b):
if cmp_order[a[p1]] > cmp_order[b[p2]]:
return False
elif cmp_order[a[p1]] < cmp_order[b[p2]]:
return True
p1 += 1
p2 += 1
return p1 == len(a)
cmp_order = {}
for i, c in enumerate(order):
cmp_order[c] = i
for i in range(1, len(words)):
if not a_smaller_than_b(words[i - 1], words[i]):
return False
return True