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)
.
1#include <stdbool.h>
2#include <string.h>
3
4bool isAlienSorted(char ** words, int wordsSize, char * order){
5 int orderIdx[26];
6 for (int i = 0; i < 26; ++i) {
7 orderIdx[order[i] - 'a'] = i;
8 }
9
10 for (int i = 0; i < wordsSize - 1; ++i) {
11 const char *word1 = words[i];
12 const char *word2 = words[i + 1];
13 int j = 0;
14 while (word1[j] == word2[j] && word1[j] != '\0') {
15 j++;
16 }
17 if (word2[j] == '\0' || (word1[j] != '\0' && orderIdx[word1[j] - 'a'] > orderIdx[word2[j] - 'a'])) {
18 return false;
19 }
20 }
21
22 return true;
23}
In C, we use an integer array orderIdx
to map each character of the alien order to its index. We then compare contiguous words using their mapped indices. If a preceding word is ever greater than a succeeding one, according to the mapped order, we return false.
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 JavaScript, we use a customized sort to arrange the words according to the alien dictionary indices and check if this order matches the original.