Wednesday, June 15, 2016

Leetcode 269: Alien Dictionary

June 15, 2016

Leetcode 269 Alien dictionary

Choose to work on a graph problem - using Topological Sorting:

Study C++ solution:
http://www.cnblogs.com/jcliBlogger/p/4758761.html

Discussion about the problem description:
https://leetcode.com/discuss/53997/the-description-is-wrong

Study C++ solution:

https://leetcode.com/discuss/54024/straightforward-c-solution?show=54024#q54024


Java solution to study:

https://github.com/jianminchen/LeetCode-Java-Solutions/blob/master/269.alien-dictionary.java

http://www.cnblogs.com/yrbbest/p/5023584.html

Julia worked on C# code:
https://gist.github.com/jianminchen/07546625d828f63e762ba03b463fe8aa
line 75, 76, after queue.peek() is called, need to call dequeue. (dead loop)

https://gist.github.com/jianminchen/a49496ea21cadcbdda7c1669216c05a5

Add more comment, where to be careful, to avoid bugs:
https://gist.github.com/jianminchen/47f516b54686080c3a68bc8c3f1d04cb

More comment, variable name refactor:
https://gist.github.com/jianminchen/85129ed50ce597f896b0f0c5a2fa5586

Read blogs:
http://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/

Comparison between 2 versions:
variable name change: graph -> dependencyList, more meaningful. The graph has nodes, dependency list, inDegree array.
Change function name: getCharSet -> getNodes
Love those comment, so helpful to get start to coding...
Left side first implementation:
for(int j=0; j < shortLength; j++)
{
...
break;
}
confusing, not very easy to follow. line 154 - line 176, 22 lines of code. The big scope to handle. 

Also, this for loop is nested loop, too many lines of code inside. 
Replacement of while loop is short, only 3 lines of code. 

graphSetup -> what we can tell here? ... later!


Question and answer:
1. Can you work on a simple example to explain the idea of your solution?

Here is the warm up for topological sorting using two strings {"wrt","wrf"}:

Review previous blog:

Warmup practice:
statistics: 1 bug, more than 60 minute to write. Totally new program
https://gist.github.com/jianminchen/58d80aa86a027af7a3e52277d15c3733
a few changes to highlight:
1. line 24 - 26 add comment what to do about graph
2. line 49 - 65 motivation talk - help to design the function
    using the graph above {"wrt","wrf"}, help to write code
3. line 72 - 74 special case words length is 1
4. line 81 - line 85 use one pointer to slide forward <- more flat code
5. line 87 add comment - no edge -> very good comment
6. line 91 - 94 first writing with a bug - prev, curr, but prev twice

Here is the comparison file:
https://github.com/jianminchen/Leetcode_C-/blob/master/Leetcode269FirstAndSecondPractice.pdf

Statistics:
time spent: 3hours +



No comments:

Post a Comment