Alien Dictionary

Graphs Hard Problems Hard
  • Fun Fact: The concept behind this problem is used in software that deals with multiple languages, internationalization or character set conversion
  • These softwares often have to determine the collation order of characters in different languages, as it can greatly vary
  • It is also used in translation software where the sequence of characters in different languages needs to be identified
  • Additionally, it provides an interesting take on sorting algorithms and graph theory, which are cornerstone concepts in various areas of software development, from database management to resource allocation

Given a sorted dictionary of an alien language having N words and K starting alphabets of a standard dictionary. Find the order of characters in the alien language.

There may be multiple valid orders for a particular test case, thus you may return any valid order. The output will be True if the order returned by the function is correct, else False denoting an incorrect order.

Examples:

Input: N = 5, K = 4, dict = ["baa","abcd","abca","cab","cad"]


Output: b d a c


Explanation: 

We will analyze every consecutive pair to find out the order of the characters.

The pair “baa” and “abcd” suggests ‘b’ appears before ‘a’ in the alien dictionary.

The pair “abcd” and “abca” suggests ‘d’ appears before ‘a’ in the alien dictionary.

The pair “abca” and “cab” suggests ‘a’ appears before ‘c’ in the alien dictionary.

The pair “cab” and “cad” suggests ‘b’ appears before ‘d’ in the alien dictionary.

So, [‘b’, ‘d’, ‘a’, ‘c’] is a valid ordering.

Input: N = 3, K = 3, dict = ["caa","aaa","aab"]


Output: c a b


Explanation: Similarly, if we analyze the consecutive pair 

for this example, we will figure out [‘c’, ‘a’, ‘b’] is 

a valid ordering.

Input: N = 3, K = 3, dict = ["abc", "bca", "cab"]

Constraints

  • 1 ≤ N, M ≤ 300
  • 1 ≤ K ≤ 26
  • 1 ≤ dict[i].length ≤ 50

Hints

  • "Compare each word with the next word and determine the first mismatching character. If ""word1"" appears before ""word2"" and the first different letter is 'x' in ""word1"" and 'y' in ""word2"", then 'x' must come before 'y' in the ordering. This gives a directed edge x → y in the graph."
  • "Track how many times each character appears as a dependent (i.e., its in-degree). Start with characters that have in-degree 0 (letters that appear first). Process letters in BFS order, ensuring that all constraints are met."

Company Tags

Roblox KPMG PayPal Target HCL Technologies Reddit PwC Qualcomm Databricks Western Digital Wayfair Splunk Instacart Teladoc Health Stripe Siemens Healthineers HashiCorp Byju's ARM Walmart Chewy NVIDIA Bloomberg Oracle MongoDB Google Microsoft Amazon Meta Apple Netflix Adobe