Trying to reiterate backward the codes so as to find common suffix of the entered array of words say:
LongestCommonSuffix(['celebration', 'opinion', 'decision', 'revision'])
To get "ion" as output
This gives me the Longest Common Prefix BUT I need to change the loop to do the same but from the end of each word in the entered list without using Binary manipulation just LOOPING
def fun(strs):
res = ''
for i in range(len(strs[0])):
for s in strs:
if i == len(s) or s[i] != strs[0][i]:
return res
res += strs[0][i]
return res
You could create a variable
common_suffix, make that equal to the first word, and then for each next word check if that word ends with that common suffix. If it doesn't, the common suffix is invalid, so try to shorten it until it does.In code:
This prints
ion.Note that this code works because
common_suffixwould be an empty string if all words are completely different. And each word ends with an empty string (for example'test'.endswith('')isTrue), so thewhileloop will always quit. You could add additional logic to break from the loop earlier, but if performance is not critical, I would stick with the simple code :-)