A valid encoding of an array of words is any reference string s and array of indices indices such that:
-
len(words) == len(indices)
-
The reference string
s
ends with the
'#'
character.
-
For each index
indices[i]
, the substring of
s
starting at
indices[i]
and running up to, but not including, the next
'#'
character is equal to
words[i]
.
Given an array of words, return the length of the shortest reference string s of any valid encoding of words.
Function Signature
def minimum_length_encoding(words: list[str]) -> int:
Rules
-
Several indices may point to the same position of
s
, so repeated words never need extra space.
-
A word is read from its index all the way to the next
'#'
, so it can only reuse part of another word's segment when it is a suffix of that word.
Constraints
-
1 <= len(words) <= 2000
-
1 <= len(words[i]) <= 7
-
words[i]
consists of only lowercase English letters.
Examples
Input: words = ["time", "me", "bell"]
Output: 10
A valid encoding is s = "time#bell#" with indices = [0, 2, 5]. "me" is a suffix of "time", so it does not need its own segment, and the length is 10.
Input: words = ["t"]
Output: 2
The only valid encoding is s = "t#", which has length 2.
Input: words = ["time", "ti", "me", "time"]
Output: 8
A valid encoding is s = "time#ti#" with indices = [0, 5, 2, 0]. "ti" is a prefix of "time", and reading from index 0 gives "time", so "ti" needs its own segment, while the second "time" reuses index 0.