Solution: Verifying an Alien Dictionary
Let's solve the Verifying an Alien Dictionary problem using the Topological Sort pattern.
Statement
You’re given an array of words with lowercase English letters in a different order, written in an alien language. The order of the alphabet is some permutation of lowercase letters of the English language.
We have to return TRUE if the given array of words is sorted lexicographically in this alien language.
Constraints:
-
words.length
-
words[i].length
order.length
- All the characters in
words[i]
andorder
are lowercase English letters.
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which to follow based on considerations such as time complexity and implementation constraints.
Naive approach
The naive approach for this problem is to iterate over the order array and words simultaneously. Start from the first word, then compare the order with all other words present in the array.
The time complexity for the naive approach is , since we’re iterating the order array and the complete array two times in nested loops. The space complexity of this naive approach is constant because we didn’t use any extra memory.
Optimized approach using topological sort
We can solve this problem using the topological sort pattern. Topological sort is used to find a linear ordering of elements that depend on or prioritize each other. For example, if A depends on B or if B has priority over A, B is listed before A in topological order.
For this problem, we’re given the array of words and the order of the alphabet. Using the order of the alphabet, we must check if the array of words is sorted lexicographically.
We can check adjacent words to see if they are in the correct order. For each word, the word on its right should be lexicographically larger, and the one on its left should be lexicographically smaller.
One thing to notice here is that we don’t need to compare all the words. We can just compare each pair of adjacent words instead. If all the pairs of adjacent words are in order, we can safely assume that the integrity is intact. Conversely, if any pair of adjacent words isn’t in order, we can assume that our order is not correct.
Let’s review the illustration to better understand the intuition described above with the help of a sample array of three words, :
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.