Problem Description
Given a list of words and a custom order of the English lowercase letters (which represents the alien language ordering), determine if the words are sorted lexicographically according to this alien dictionary order.
Key Insights
- Create a mapping from each character to its rank based on the provided alien order.
- Compare every adjacent pair of words to ensure the first one is not greater than the next.
- In comparing two words, iterate over characters and decide order based on the mapping.
- Handle the prefix case: if two words match up to the length of the shorter word, the shorter must come first.
Space and Time Complexity
Time Complexity: O(n * m) where n is the number of words and m is the average length of the words. Space Complexity: O(1) aside from the input space, since the mapping is fixed at 26 characters.
Solution
The solution uses a hash map (or dictionary) to convert each character in the alien order into its corresponding index. This allows for constant time lookups when comparing characters between words. We then iterate pairwise through the list of words and for each pair, compare the characters until a difference is found. If the current character from the first word ranks higher than that from the second word, or if one word is a prefix of the other (and the longer comes first), then the list is not sorted. If no invalid order is encountered, return true.