Given a list of words. We encode it by writing a reference string S and a list of indexes A. For each index, we will recover the word by reading from the reference string from that index until we reach a “#” character in S. The task is to find the length of the shortest reference string S possible that encodes the given words.
Examples :
Input : Words = ["time", "me", "bell"] Output : 10 Explanation : S = "time#bell#" and Indexes = [0, 2, 5]. Input : Words = ["w3colleges", "leges", "w3c"] Output : 15 Explanation : S = "w3colleges#w3c#" and Indexes = [0, 5, 11].
Approach :
If a word P is a suffix of Q, then it does not need to be considered, as the encoding of word Q in the reference string will also encode P. For example, if “leges” and “w3colleges” is in words, we can throw out “leges” without changing the answer.
If a word Q does not have any other word P (in the list of words) that is a suffix of Q, then Q must be part of the reference string.
Thus, our problem boils down to remove word from the list such that no word is a suffix of another. The final answer would be sum(len(word) + 1 for word in words).
Implementation :
Python3
# Function to find length of encoded string
def minimumLengthEncoding(words):
# Make unique set of words
good = set(words)
for word in words:
# Discard word if it is suffix of another word
for k in range(1, len(word)):
good.discard(word[k:])
# Return final answer
return sum(len(word) + 1 for word in good)
# Program Code
Words = ["time", "me", "bell"]
# Function call to print required answer
print(minimumLengthEncoding(Words))
10