Merge words by head-tail chaining | Yahoo Interview Question