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)
.
1function isAlienSorted(words, order) {
2 const orderMap = new Map(order.split('').map((char, idx) => [char, idx]));
3
4 const isInOrder = (word1, word2) => {
5 let i = 0;
6 while (i < word1.length && i < word2.length) {
7 if (word1[i] !== word2[i]) {
8 return orderMap.get(word1[i]) < orderMap.get(word2[i]);
9 }
10 i++;
11 }
12 return word1.length <= word2.length;
13 };
14
15 for (let i = 0; i < words.length - 1; i++) {
16 if (!isInOrder(words[i], words[i + 1])) {
17 return false;
18 }
19 }
20
21 return true;
22}
In JavaScript, we map character indices using Map
and check each word pair using the auxiliary function isInOrder
. This function returns a boolean indicating if the words are in the correct 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 Python, we use the sorted
function with a lambda function to sort words based on the alien dictionary order. Then we check if the sorted version matches the input.