Update appNew update is available. Click here to update.
Last Updated: 20 Feb, 2021
Ninja And Alien
Hard
Problem statement

An alien spaceship arrived at our planet Earth. An alien dropped his dictionary of words on the way back to his planet. Ninja found that dictionary and now wants to create the order of the characters of that language. Help ninja in creating the order of the characters with the help of the list of words given as were found in the Alien’s dictionary.

Example:
Let us assume that we have a list of words found in the dictionary in the same order as given: [β€œbaa”, β€œabcd”, β€œabca”, β€œcab”, β€œcad”]

Now, ninja needs to find the order of the characters used in these strings.

The order would be: β€˜b’, β€˜d’, β€˜a’, β€˜c’, because β€œbaa” comes before β€œabcd”, hence β€˜b’ will come before β€˜a’ in the order, similarly because, β€œabcd” comes before β€œabca”, β€˜d’ will come before β€˜a’. And so on.
Note:
A certain list of words might have more than one correct order of characters. In such cases, you need to find the smallest in normal lexicographical order. In the case of INVALID ORDER, simply return an empty string.
Invalid Order:
words = [β€œaba”, β€œbba”, β€œaaa”]. 
In this case, no valid order is possible because, from the first two words, we can deduce β€˜a’ should appear before β€˜b’, but from the last two words, we can deduce β€˜b’ should appear before β€˜a’ which is not possible.
More than one correct order:
words = [β€œca”, β€œcb”]. 
In this case, we only know that β€˜b’ will come after β€˜a’ in the order of characters, but we don't have any knowledge of β€˜c’. So, the valid correct orders can be = β€œabc”, β€œcab”, β€œacb”. Out of these, β€œabc” is lexicographically smallest, hence it will be printed.
Input Format:
The first line contains a single integer β€˜T’ representing the number of test cases. 

The first line of each test case will contain an integer β€˜N’, which denotes the number of words in the dictionary.

The second line of each test case will contain β€˜N’ space-separated strings which denote the words of the dictionary.
Output Format:
For each test case, print the order of characters.

Output for every test case will be printed in a separate line.
Constraints:
1 <= T <= 10
1 <= N <= 300
0 <= size <= 100

Time limit: 1 sec
Approaches

01Approach

The idea behind this approach is to create a graph of the words of the dictionary and then apply the topological ordering of the graph. 

 

A topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge u v from vertex u to vertex v, u comes before v in the ordering.

 

The approach is to take two words from the array of words and then compare characters of both words and find the first character that is not the same in the words.

 

Then, create an edge in the graph from the first different character of the first word to the second word.

 

Finally, apply topological sorting in the above-created graph.

 

Let us understand this better by dividing the complete solution into two parts:

 

  1. Graph Creation:
    • We will use unordered_map to store the graph. The graph will be created by using below steps:
      • We’ll start with two words, let’s say a and b. Now we find the smaller word from the two, so that we could just traverse to that position.
        • Let’s say a has 3 characters and b has 5 characters. Now in order to find the first mismatched character we traverse from start to the length of the smaller word and check each character, until we find the first mismatched character.
        • Now, we  simply create an edge between the first mismatched character of the first word to the second word.
        • Continue this process until all the edges are created.
        • Now, we will have a graph created with 1st mismatched character from each word to the other.
  2. Now, apply the topological sort in the created graph in order to find the required order.
  3. Topological Sorting:
    • The topological sorting algorithm is used in directed graphs(like the one we created), in which we need to find an order of edges such that every edge leads from the vertex of a smaller value assigned to the larger value. To read more about topological sorting you can refer: https://cp-algorithms.com/graph/topological-sort.html
    • Basically, we start from a vertex let’s say v and run along all edges that are outgoing from the same. This will not move along the edges for which the destination vertex has already been visited.
      • Continue the same process from the rest of the edges and then start from them,
      • By the end of this method, all vertices would be reached from the starting vertex v either directly or indirectly.
      • Finally, we will use a queue to store the topological order of all vertices.

 

Algorithm + Pseudo Code:

  1. Define a map let’s say β€œdegree”.
  2. Define another map let’s say β€œgraph”.
  3. Now initialize i from i = 0 to i < size of words, while updating i by one in each traversal and, do βˆ’
    • Initialize another var j from j = 0 to j < size of words, while updating j by one in each traversal and, do βˆ’
      • degree[words[i,  j]] := 0
  4. Next initialize i from i = 0 to i < (size of words - 1), while updating i by one in each traversal and, do βˆ’
    • Initialise a var β€œmini” := minimum of size of words[i] and size of words[i + 1]. In order to find the smaller word, we could traverse only to that value.
    • Initialise j from j = 0 to j < mini, while updating j by one in each traversal and, do βˆ’
      • Store in a var x := words[i, j]
      • Store in a var y := words[i + 1, j]
      • If x is not equal to y, then βˆ’ (First different character found)
        • insert y at the end of β€œgraph[x]”
        • (increase degree[y] by 1)
        • Come out from the loop
  5. β€œresult” := Initialise a blank string to store the final order
  6. Initialise a queue β€œque”
  7. For each key-value pair let’s say β€œiter” in β€œdegree”, do βˆ’
    • if value of β€œiter” is same as 0, then βˆ’
      • insert key of it into β€œque”
  8. Now, while (not β€œque” is empty), do βˆ’
    1. x := first element of β€œque”
    2. delete element from β€œque”
    3. result := result + x
    4. for every element let’s say β€œelem” in β€œgraph” do βˆ’
      • decrease degree[elem] by 1
      • Now, if degree[elem] is same as 0, then βˆ’
        • insert β€œelem” into β€œque”
      • (increase β€œelem” by 1)
  9. return (if size of β€œresult” is same as the size of β€œdegree”, then result, otherwise return a blank string)

 

Keep in mind the following cases: 

  1. The longer string with the same prefix comes first, will make it an invalid case.
  2. In case of more than one correct order, simply return the lexicographical smallest order.