Sponsored
Sponsored
This approach involves converting each character in the alien order to an index, which can be used to easily compare words. The idea is to take the given order of the language and map each character to its position in the order. Then, we can compare words by comparing their mapped indices.
Time Complexity: O(N)
, where N
is the total number of characters in all words. Space Complexity: O(1)
.
1def isAlienSorted(words: List[str], order: str) -> bool:
2 order_idx = {char: idx for idx, char in enumerate(order)}
3
4 def is_in_order(w1, w2):
5 length = min(len(w1), len(w2))
6 for i in range(length):
7 if w1[i] != w2[i]:
8 return order_idx[w1[i]] < order_idx[w2[i]]
9 return len(w1) <= len(w2)
10
11 for i in range(len(words) - 1):
12 if not is_in_order(words[i], words[i + 1]):
13 return False
14 return True
In Python, we create a dictionary to store the order of each character. We define an is_in_order
function to check if two words are in the required order based on the alien dictionary. We iterate over word pairs and return false if any are out of order.
This approach employs a custom comparator to sort the words based on the alien order. We first map the order and then define a comparator that sorts based on this map. We check if the sorted version of the words matches the original order, indicating that they were sorted correctly in the alien dictionary.
Time Complexity: O(N log N)
due to sorting. Space Complexity: O(1)
.
1
In C, we define a custom comparison function that utilizes the mapped order to determine the lexicographic order of words. We then iterate through the words to ensure they are sorted.