Saturday, March 31, 2012

Given a dictionary of words find the ranking of characters

You are given a dictionary with set of words i.e. in the dictionary words are arranged in special lexicographical order. The lexicographical order is what you need to find. i.e. this dictionary is not arranged like a standard dictionary where a < b < c ... < z I is based on different character ranking you need to find that ranking.

Solution:
Consider subset of dictionary order

LBD
LBK
EMN
ERQ
GLQ
HFG

Look at first character of words. We know L < E < G < H
Consider second cloumn characters whose first character are same eg (EMN, ERQ) we know M < R
consider third column whose first two columns are same (LBD, LBK) we know D < K

Now consider that each character is a node in the graph when we find a relations ship that character1 < character2 we add directed edger from character1->character2

Using above method we traverse through all columns and build the graph.

In next step the character which comes first will have incoming degree 0. That will character which comes first we visit that node and remove it. As a result we will find next node with incoming degree 0 that will be character with next ranking. We will continue doing this until we have visited all nodes.

If at any stage we get two nodes with indegree of 0 we do not have enough input. Also if the input is given that there is a cycle in the graph solution will need to detect such bad inputs.

No comments:

Post a Comment