Verifying an Alien Dictionary
We are given a list of words and a specific order of characters in an alien language. We need to determine if the words are sorted lexicographically according to this alien language.
Approach
Create a Mapping: Create a mapping of each character to its index according to the given order. This will help us compare the characters in the words.
Compare Adjacent Words: Iterate through the list of words and compare each word with the next one to check if they are sorted.
Compare Characters: For each pair of adjacent words, compare their characters one by one. If we find a character that is larger in the first word than in the second, return False, as this means the words are not sorted. If the characters are equal, continue to the next character. If the first word is a prefix of the second, continue to the next pair of words.
Handle Edge Case: If one word is a prefix of the other (e.g., “app” and “apple”), the shorter word should come first. If not, return False.
Return True: If all adjacent words are sorted, return True.
Code
|
|
Example
- Input:
words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
- Output:
true
- Explanation: Since ‘h’ comes before ’l’ in this language, the sequence is sorted.
Insights
- Time Complexity: The time complexity of this solution is (O(n \cdot m)), where (n) is the number of words, and (m) is the maximum length of a word.
- Space Complexity: The space complexity is (O(1)), as we are only using a constant amount of extra space (not counting the input itself).
- Utilizing Custom Order: The solution efficiently utilizes the given custom order by mapping the characters to their indices, making it easy to compare them.
|
|