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)
.
1using System;
2
3public class Solution {
4 public bool IsAlienSorted(string[] words, string order) {
5 int[] index = new int[26];
6 for (int i = 0; i < order.Length; i++) {
7 index[order[i] - 'a'] = i;
8 }
9 for (int i = 0; i < words.Length - 1; i++) {
10 if (!InOrder(words[i], words[i+1], index)) {
11 return false;
12 }
13 }
14 return true;
15 }
16
17 private bool InOrder(string word1, string word2, int[] index) {
18 int minLength = Math.Min(word1.Length, word2.Length);
19 for (int i = 0; i < minLength; i++) {
20 if (word1[i] != word2[i]) {
21 return index[word1[i] - 'a'] < index[word2[i] - 'a'];
22 }
23 }
24 return word1.Length <= word2.Length;
25 }
26}
In C#, we map the alien order to indices and use a helper InOrder
function to validate each word pair. If a pair is not in order, we stop and 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 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.