Finding the valid letter sequence [reviewed]

Problem 

There's a new language which uses the latin alphabet. However, you don't know the order among letters.

  You receive a list of words lexicographically sorted by the rules of this new language. From this list, derive one valid particular ordering of letters in the language.

For example, given list of words, {"abcdefo", "begz", "hijk", "abcedefgh", "ikom"}

One valid sequence would be {abcdefom}.
Before, reasoning about the algorithm. Let think about what we would do to understand the sequence  among letters, given list of words. Drawing the following diagram on the paper would give us more clear picture.


Basically, we first need to build the directed graph and choose the one node and following each node's edge and print out its value until we encounter the node without any outgoing edges.


Here is the complete code running in $O( N log N)$, where N is the total number of letters in the array.




However, if the question is to print out the valid sequence starting from the first letter. We need to know the topological sequence as well, which leads to the following code.



Practice statistic

30:26 : to write up the code.
7:57: to verify the correctness
11:16: fix up the code again

Overcomplicated the solution adding unnecessary topological DFS, and sorting.


UPDATE(2019-07-26): solve this problem again, using graph and DFS w/o backtracking.

Here is the python version of solution.

Statistics:

9:00: to come up with algorithm
15:00: to write the code. (incomplete test code)
1:00: to finish the test code

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Stock price processing problem