Imagine you have a list of words and you want to create a reference string that can represent all of them using the minimum amount of space. The encoding works like this:
- Create a reference string
sthat ends with '#' - For each word, store an index pointing to where that word appears in the reference string
- Each word must be followed by a '#' character in the reference string
Example: For words ["time", "me", "bell"], one valid encoding could be the reference string "time#bell#" with indices [0, 2, 5], but a shorter encoding would be "time#bell#" with indices [0, 2, 5].
Your goal is to find the minimum length of such a reference string. The key insight is that if one word is a suffix of another (like "me" is a suffix of "time"), you can save space by only storing the longer word!
Input & Output
Visualization
Time & Space Complexity
Building trie takes O(nm) where n is number of words and m is average length, checking each word takes O(m)
Trie can store up to nm characters in worst case when no words share common suffixes
Constraints
- 1 โค words.length โค 2000
- 1 โค words[i].length โค 7
- words[i] consists of only lowercase letters