Short Encoding of Words — LeetCode 820 Python Solution

MediumTrieArrayHash TableString
Problem
#820
Pattern
Trie
Reading time
5 min

The 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].

Example

Input
words = ["time", "me", "bell"]
Output
10
Explanation
A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].

Python solution

Python
class Trie:
    def __init__(self) -> None:
        self.children = [None] * 26


class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        root = Trie()
        for w in words:
            cur = root
            for c in w[::-1]:
                idx = ord(c) - ord("a")
                if cur.children[idx] == None:
                    cur.children[idx] = Trie()
                cur = cur.children[idx]
        return self.dfs(root, 1)

    def dfs(self, cur: Trie, l: int) -> int:
        isLeaf, ans = True, 0
        for i in range(26):
            if cur.children[i] != None:
                isLeaf = False
                ans += self.dfs(cur.children[i], l + 1)
        if isLeaf:
            ans += l
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 820. Short Encoding of Words is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 820. Short Encoding of Words?
LeetCode 820. Short Encoding of Words is rated Medium on LeetCode.
What is the time complexity of LeetCode 820. Short Encoding of Words?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 820. Short Encoding of Words?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 820. Short Encoding of Words cover?
LeetCode 820. Short Encoding of Words is tagged Trie, Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview