#953
Verifying an Alien Dictionary
EasyArrayHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of comparing each word with the next in a brute-force manner, we can use a single pass with a mapping of characters to their indices to efficiently determine the order of words. This reduces unnecessary comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping of each character in the alien order to its index.
- 2Step 2: Iterate through the list of words, comparing each word with the next one using the mapping.
- 3Step 3: If any word is found to be out of order, return false; otherwise, return true after all checks.
solution.py16 lines
1# Full working Python code
2order_map = {char: index for index, char in enumerate(order)}
3def isAlienSorted(words, order):
4 for i in range(len(words) - 1):
5 if not is_sorted(words[i], words[i + 1], order_map):
6 return False
7 return True
8
9def is_sorted(word1, word2, order_map):
10 min_length = min(len(word1), len(word2))
11 for i in range(min_length):
12 if order_map[word1[i]] < order_map[word2[i]]:
13 return True
14 elif order_map[word1[i]] > order_map[word2[i]]:
15 return False
16 return len(word1) <= len(word2)ℹ
Complexity note: The time complexity is O(n) because we only pass through the list of words once, and the space complexity is O(n) due to the storage of the order mapping.
- 1Understanding the mapping of characters to their indices is crucial for comparing words in the alien language.
- 2Lexicographical order is determined by character comparison, similar to how we compare numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.