In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 20order.length == 26words[i] and order are English lowercase letters.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.
In C, we use an integer array orderIdx to map each character of the alien order to its index. We then compare contiguous words using their mapped indices. If a preceding word is ever greater than a succeeding one, according to the mapped order, we return false.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N), where N is the total number of characters in all words. Space Complexity: O(1).
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.
In C, we define a custom comparison function that utilizes the mapped order to determine the lexicographic order of words. We then iterate through the words to ensure they are sorted.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N log N) due to sorting. Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Mapping Order Using Indexes | Time Complexity: |
| Using Custom Comparator | Time Complexity: |
G-26. Alien Dictionary - Topological Sort • take U forward • 221,163 views views
Watch 9 more video solutions →Practice Verifying an Alien Dictionary with our built-in code editor and test cases.
Practice on FleetCode