Find the length of longest chain formed using given words in String

Bhargav Modi picture Bhargav Modi · Feb 21, 2015 · Viewed 7.1k times · Source

Okk As programmer we love get involved in logic building but that is not the case some time we become blank over some type of puzzle as below mentioned. Let me declare that this is not any kind of homework or job stuff it simply a logic and performance practice puzzle.Okk the puzzle of given an Strings` with comma separated words like

String S= peas,sugar,rice,soup

Now crux is to find out length of longest chain of the words like last character of word should be the first character of next word and so on to create a longest possible chain and finally to calculate the length of that chain.

Now I had tried to figure out some sort of solution like

  1. split the string with comma
  2. add them in list
  3. sort that list etc

but now how to develop further logic As I m little poor over logic development,Help is appreciated and if above half logic is not proper as it should be than what must the simple sort and perfect way to get the length of the longest chain of words.

Summary
input: String S= peas,sugar,rice,soup.
output: 4 length of words (peas->sugar->rice->soup) or (soup->peas->sugar->rice) etc

Answer

AlexR picture AlexR · Feb 21, 2015

Once you have list (or array) you can iterate over the array checking your condition (equality of last letter of n-th words with the first letter of first word) and increase counter each time. Once the condition is false just escape the loop. Your counter will hold value you need.