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 <string>
2#include <vector>
3using namespace std;
4
5bool isAlienSorted(vector<string>& words, string order) {
6 vector<int> orderIdx(26);
7 for (int i = 0; i < order.size(); ++i) {
8 orderIdx[order[i] - 'a'] = i;
9 }
10
11 for (int i = 0; i < words.size() - 1; ++i) {
12 const string& w1 = words[i];
13 const string& w2 = words[i + 1];
14 size_t j = 0;
15 while (j < w1.length() && j < w2.length() && w1[j] == w2[j]) {
16 ++j;
17 }
18 if (j < w2.length() && (j >= w1.length() || orderIdx[w1[j] - 'a'] <= orderIdx[w2[j] - 'a'])) continue;
19 if (j == w2.length() || orderIdx[w1[j] - 'a'] > orderIdx[w2[j] - 'a']) return false;
20 }
21 return true;
22}
In C++, we achieve a similar outcome by using a vector
to store the order mappings. We iterate through each word pair and compare based on the mapped indices. If a lexicographic order mismatch is detected, 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 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.