953. Verifying an Alien Dictionary
Problem
An alien language uses the lowercase letters in a different order, given as the string order. Decide whether words is sorted lexicographically in that alphabet (a word sorts before any longer word it is a prefix of).
Example: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" → true
Map each letter to its rank; compare adjacent words at their first differing character. If none differ, the shorter word must come first.
Complexity: O(total characters).
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
rank = {ch: i for i, ch in enumerate(order)}
keys = [[rank[ch] for ch in w] for w in words]
return all(a <= b for a, b in zip(keys, keys[1:])) # list comparison = lexicographic
assert Solution().isAlienSorted(["hello", "leetcode"], "hlabcdefgijkmnopqrstuvwxyz") is True
assert Solution().isAlienSorted(["word", "world", "row"], "worldabcefghijkmnpqstuvxyz") is False
assert Solution().isAlienSorted(["apple", "app"], "abcdefghijklmnopqrstuvwxyz") is False
class Solution {
public boolean isAlienSorted(String[] words, String order) {
int[] rank = new int[26];
for (int i = 0; i < 26; i++) rank[order.charAt(i) - 'a'] = i;
for (int w = 0; w + 1 < words.length; w++) {
String a = words[w], b = words[w + 1];
int i = 0;
while (i < a.length() && i < b.length() && a.charAt(i) == b.charAt(i)) i++;
if (i == a.length() || i == b.length()) { if (a.length() > b.length()) return false; }
else if (rank[a.charAt(i) - 'a'] > rank[b.charAt(i) - 'a']) return false;
}
return true;
}
}
func isAlienSorted(words []string, order string) bool {
var rank [26]int
for i := 0; i < len(order); i++ {
rank[order[i]-'a'] = i
}
less := func(a, b string) bool { // a <= b in the alien order
for i := 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
return rank[a[i]-'a'] < rank[b[i]-'a']
}
}
return len(a) <= len(b)
}
for i := 1; i < len(words); i++ {
if !less(words[i-1], words[i]) {
return false
}
}
return true
}