You want to pack a list of words into one reference string. The string is made of pieces, each ending in #. Every word must be readable from it: there has to be a starting position where reading forward up to the next # gives exactly that word.
A word that is the ending of another word can share its piece. For example lane can be read from inside plane# by starting one letter later. How short can the reference string be? Return the smallest possible length that still covers every word.
Example 1
Input: words = ["cat", "at", "dot"] Output: 8 Why: "cat#dot#"; at is read from inside cat#
2 more examples and the constraints
Example 2
Input: words = ["plane", "ne", "sky", "lane"] Output: 10 Why: "plane#sky#" covers lane and ne too
Example 3
Input: words = ["go", "go"] Output: 3 Why: "go#" serves both copies
Constraints
- 1 ≤ number of words ≤ 2,000
- 1 ≤ length of each word ≤ 7
- Words use lower-case English letters only
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n² · k)
- Remove suffixes from a setO(n · k²)
- Trie of reversed wordsO(n · k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 words of 7 letters | Verdict |
|---|---|---|---|
| Check every pair | O(n² · k) | Mention it, then move on | |
| Remove suffixes from a set | O(n · k²) | Short and fast | |
| Trie of reversed words | O(n · k) | Best; one pass per letter |
n = number of words, k = longest word length (at most 7).
Edge cases to test
- A single word. ["k"] needs "k#", length 2.
- Duplicate words. ["go", "go"] needs one piece, length 3.
- Prefixes do not share. "pla" cannot be read from "plane#", because reading would run on to the e.
- A chain of suffixes. "e", "ne", "ane", "lane" all fit in "lane#".
- No sharing at all. Every word pays its length + 1.
Common mistakes
- Sharing prefixes instead of suffixes; a read always runs to the next #.
- Counting duplicate words twice.
- Forgetting the # after each kept word, which is the + 1.
How to talk through it
- 1Clarify. Can words repeat? Must each word end right before a #?
- 2Find the rule. A word is free exactly when it is the ending of another word.
- 3Give the pair check. Compare all pairs; O(n² · k) is slow for 2,000 words.
- 4Remove suffixes or build a reversed trie. Either finds the free words in near-linear time.
- 5Test out loud. Run duplicates, a suffix chain and a single word.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?