22. Alien Dictionary
The problem can be found at the following link: Question Link
Problem Description
Given a sorted dictionary of an alien language containing N words and K starting alphabets of a standard dictionary, find the order of characters in the alien language.
Example 1:
Input:
n = 5, k = 4
dict = {"baa","abcd","abca","cab","cad"}Output:
1Explanation: The order of characters is 'b', 'd', 'a', 'c'. Words are sorted, so "baa" comes before "abcd", indicating 'b' before 'a'.
Example 2:
Input:
n = 3, k = 3
dict = {"caa","aaa","aab"}Output:
1Explanation: The order of characters is 'c', 'a', 'b'. Words are sorted, so "caa" comes before "aaa", indicating 'c' before 'a'.
My Approach
Graph Construction:
Compare adjacent words in the dictionary to determine the first mismatched character, which indicates the order.
Build a directed graph where each character points to the character that comes after it.
Topological Sorting:
Perform topological sorting on the graph to determine the correct order of characters in the alien language.
Use DFS (Depth-First Search) to ensure that the order is consistent with the constraints imposed by the dictionary.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n * |s| + k), where
nis the number of words,|s|is the average length of the words, andkis the number of unique characters.Expected Auxiliary Space Complexity: O(k), as we are storing a graph with
knodes and additional space for recursion stack during DFS.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated