Skip to main content
LeetCode 820, Medium. Topics: Array, Hash Table, String, Trie. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

Problem

A valid encoding of an array of words is any reference string s and array of indices indices such that:
  • words.length == indices.length
  • The reference string s ends with the '#' character.
  • For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string * s * possible of any valid encoding of * words.

Examples

Constraints

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • words[i] consists of only lowercase letters.
Follow up: Can you solve it in O(n * max(words[i].length)) time using a Trie?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026