Verifying an Alien Dictionary
Easy · Arrays & Hashing · Explanation and code example
Comparing adjacent words
How it works
For a list to be sorted, each adjacent pair must be in the correct order. Instead of sorting, we can directly verify that each word is lexicographically less than or equal to the next word according to the alien order. This avoids the overhead of sorting.
Steps
- Create a mapping from each character to its index position in the
orderstring. - Iterate through adjacent pairs of words (
w1,w2) in the array. - Compare characters at each position until a difference is found or one word ends.
- If
w1is longer thanw2and all compared characters match, returnfalse(prefix violation). - If characters differ, check that
w1's character has a smaller index thanw2's character in alien order. If not, returnfalse. - If all adjacent pairs pass validation, return
true.
Complexity
- Time complexity:
O(n * m) - Space complexity:
O(1)since we have26different characters.
Where
nis the number of words andmis the average length of a word.
Things to watch for
Ignoring the Prefix Case
When comparing two words where one is a prefix of the other (e.g., "apple" and "app"), the shorter word must come first. If the longer word appears before its prefix in the list, the order is invalid. Many solutions forget to check this case and only compare differing characters.
Breaking Too Early or Too Late in Character Comparison
When comparing adjacent words character by character, you must break out of the loop as soon as you find the first differing character. Continuing to compare after finding a difference can lead to incorrect conclusions, as only the first difference determines the relative order of two words.
Python code example
from typing import List
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
order_index = {c: i for i, c in enumerate(order)}
for i in range(len(words) - 1):
w1, w2 = words[i], words[i + 1]
for j in range(len(w1)):
if j == len(w2):
return False
if w1[j] != w2[j]:
if order_index[w1[j]] > order_index[w2[j]]:
return False
break
return True
C++ code example
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
int orderIndex[26] = {0};
for (int i = 0; i < order.size(); ++i)
orderIndex[order[i] - 'a'] = i;
for (int i = 0; i < words.size() - 1; ++i) {
string w1 = words[i], w2 = words[i + 1];
int j = 0;
for (; j < w1.size(); ++j) {
if (j == w2.size()) return false;
if (w1[j] != w2[j]) {
if (orderIndex[w1[j] - 'a'] > orderIndex[w2[j] - 'a'])
return false;
break;
}
}
}
return true;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.