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)
.
1import java.util.*;
2
3class Solution {
4 public boolean isAlienSorted(String[] words, String order) {
5 int[] orderIdx = new int[26];
6 for (int i = 0; i < order.length(); i++) {
7 orderIdx[order.charAt(i) - 'a'] = i;
8 }
9
10 for (int i = 0; i < words.length - 1; i++) {
11 if (!inOrder(words[i], words[i + 1], orderIdx)) {
12 return false;
13 }
14 }
15
16 return true;
17 }
18
19 private boolean inOrder(String word1, String word2, int[] orderIdx) {
20 int minLength = Math.min(word1.length(), word2.length());
21 for (int i = 0; i < minLength; i++) {
22 if (word1.charAt(i) != word2.charAt(i)) {
23 return orderIdx[word1.charAt(i) - 'a'] < orderIdx[word2.charAt(i) - 'a'];
24 }
25 }
26 return word1.length() <= word2.length();
27 }
28}
In Java, we use an integer array to map the order of characters. We implement a helper function inOrder
to compare each word pair based on the mapped indices. If a word pair is out of 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 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.