Short Encoding of Words

Medium · Tries · Array · Hash Table · String · Trie

Problem

A valid encoding of an array words is a reference string s together with an array of indices indices such that:

Return the length of the shortest possible reference string s.

For example, words = ["time", "me", "bell"] can be encoded as s = "time#bell#" with indices = [0, 2, 5]: "me" is read from inside "time#".

Examples

Input: words = ["bell","ell","ring"]
Output: 10

"ell" is the end of "bell", so s = "bell#ring#" with indices [0, 1, 5]: length 10.

Input: words = ["ab","ab"]
Output: 3

Both copies point at "ab#".

Input: words = ["xy","z"]
Output: 5

Neither word ends the other: "xy#z#".

Constraints

Approaches

Follow-up

If words could share beginnings instead of endings, the same trie works without reversing. And if you need the string itself, keep the uncovered words and join them. Both are use cases below.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…