Skip to content
BytePatterns

Shortest Encoding of a Word List

MediumTries#trie#suffix-sharing~25m

Problem

A list of lowercase words is stored as one reference string in which every word ends with a #, and each word is read by starting at some index and stopping at the next #. A word that is a suffix of another word therefore needs no space of its own: me can be read inside time#. Return the length of the shortest reference string that can encode all the words.

Examples

Input:  words = ["time", "me", "bell"]
Output: 10
Why:    time#bell# holds all three, with me read from index 2
Input:  words = ["atom", "tom", "m", "bat"]
Output: 9
Why:    atom#bat#, since tom and m are both suffixes of atom
Input:  words = ["me", "me"]
Output: 3
Why:    edge case, a repeated word is encoded once

Hints

0 / 3

Stuck on the idea rather than the code? Trie vs Hash Set covers it.