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:

1

Explanation: 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:

1

Explanation: The order of characters is 'c', 'a', 'b'. Words are sorted, so "caa" comes before "aaa", indicating 'c' before 'a'.

My Approach

  1. 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.

  2. 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 n is the number of words, |s| is the average length of the words, and k is the number of unique characters.

  • Expected Auxiliary Space Complexity: O(k), as we are storing a graph with k nodes 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