Skip to content
Problem 820 · LeetCode 820(opens in a new tab)

Short Encoding of Words

MediumHash tables

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.

Try it on LeetCode(opens in a new tab)
  1. Check every pairO(n² · k)
  2. Remove suffixes from a setO(n · k²)
  3. Trie of reversed wordsO(n · k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 2,000 words of 7 lettersVerdict
Check every pairO(n² · k)
Mention it, then move on
Remove suffixes from a setO(n · k²)
Short and fast
Trie of reversed wordsO(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

  1. 1Clarify. Can words repeat? Must each word end right before a #?
  2. 2Find the rule. A word is free exactly when it is the ending of another word.
  3. 3Give the pair check. Compare all pairs; O(n² · k) is slow for 2,000 words.
  4. 4Remove suffixes or build a reversed trie. Either finds the free words in near-linear time.
  5. 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?