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)
.
1using System.Collections.Generic;
public class Solution {
public bool IsAlienSorted(string[] words, string order) {
int[] index = new int[26];
for (int i = 0; i < order.Length; i++) {
index[order[i] - 'a'] = i;
}
List<string> sortedWords = new List<string>(words);
sortedWords.Sort((w1, w2) => {
int minLength = Math.Min(w1.Length, w2.Length);
for (int i = 0; i < minLength; i++) {
if (w1[i] != w2[i]) {
return index[w1[i] - 'a'] - index[w2[i] - 'a'];
}
}
return w1.Length - w2.Length;
});
for (int i = 0; i < words.Length; i++) {
if (!words[i].Equals(sortedWords[i])) return false;
}
return true;
}
}
In C#, we use a custom Sort method to organize words based on mapped alien indices and then verify that the sorted list matches the input list.