cswork / templatesOpen the Line 500 list

STOP 34 · DESIGN & BITS

Dictionaries, File Systems, and Serialization

Trie nodes hold children and counts O(length) per operation

Contest ratings Rating 1479–Rating 1479· median Rating 1479(1 of 6 problems rated by zerotrac)

Open the Line 500 list · stop 34 · 6 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 2 companies · in 2 reportsApple 1, DoorDash 1

Warm up with this one

LC 676Implement Magic DictionaryMedium
Stuck? Peek at the approach

Design dictionary queries allowing exactly one character change, distinguishing exact matches from valid approximate matches.

Key points

  1. Each node is a prefix; insert and lookup walk down one character at a time, so the cost depends only on the word length.
  2. Counts on the nodes (words passing through, words ending here) make prefix counting and deletion O(L).
  3. Serialize a binary tree in preorder with a null marker such as "#", and deserialize by reading it back in the same order.

Common pitfalls

  • Mixing up search (a whole word) and startsWith (a prefix) by not checking the end-of-word marker.
  • A fixed 26-way array assumes lowercase letters; use a hash map of children for uppercase, digits or Unicode.
  • Serializing without separators makes multi-digit and negative values impossible to parse back.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Trie · insert and search

Insert cat, car, cart, dog, do, then search car, cap, do

Try your own input
·
CurrentDiscovered / computedAnswer
Nodes
1
Words
0

Only an empty root. Each edge is one character; a path spells a prefix.

InvariantThe path from the root to any node is a prefix; only nodes with a word written under them end a whole word.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 676, with it.

Python
class Trie:
    def __init__(self):
        self.children: dict[str, Trie] = {}
        self.prefix = 0  # words passing through this node
        self.words = 0  # words ending exactly here

    def insert(self, word: str) -> None:
        node = self
        for ch in word:
            node = node.children.setdefault(ch, Trie())
            node.prefix += 1
        node.words += 1

    def _walk(self, s: str):
        node = self
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def count_word(self, word: str) -> int:
        node = self._walk(word)
        return node.words if node else 0

    def count_prefix(self, prefix: str) -> int:
        node = self._walk(prefix)
        return node.prefix if node else 0
C++
// Lowercase words. Nodes live in one vector; child index 0 means "none" (0 is the root).
class Trie {
    struct Node {
        array<int, 26> next{};
        int prefix = 0, words = 0;  // words passing through / ending exactly here
    };
    vector<Node> nodes = vector<Node>(1);

    int walk(const string& s) const {  // node index for s, or -1
        int cur = 0;
        for (char ch : s)
            if (!(cur = nodes[cur].next[ch - 'a'])) return -1;
        return cur;
    }

public:
    void insert(const string& word) {
        int cur = 0;
        for (char ch : word) {
            int c = ch - 'a';
            if (!nodes[cur].next[c]) {
                nodes[cur].next[c] = nodes.size();
                nodes.emplace_back();  // may reallocate: never hold a Node& across this
            }
            cur = nodes[cur].next[c];
            nodes[cur].prefix++;
        }
        nodes[cur].words++;
    }

    int countWord(const string& word) const {
        int i = walk(word);
        return i < 0 ? 0 : nodes[i].words;
    }

    int countPrefix(const string& prefix) const {
        int i = walk(prefix);
        return i < 0 ? 0 : nodes[i].prefix;
    }
};
Java
// Lowercase words.
class Trie {
    private final Trie[] next = new Trie[26];
    private int prefix, words; // words passing through / ending exactly here

    void insert(String word) {
        Trie node = this;
        for (char ch : word.toCharArray()) {
            int c = ch - 'a';
            if (node.next[c] == null) node.next[c] = new Trie();
            node = node.next[c];
            node.prefix++;
        }
        node.words++;
    }

    private Trie walk(String s) {
        Trie node = this;
        for (char ch : s.toCharArray()) {
            node = node.next[ch - 'a'];
            if (node == null) return null;
        }
        return node;
    }

    int countWord(String word) {
        Trie node = walk(word);
        return node == null ? 0 : node.words;
    }

    int countPrefix(String prefix) {
        Trie node = walk(prefix);
        return node == null ? 0 : node.prefix;
    }
}
Go
// Trie stores lowercase words.
type Trie struct {
	next   [26]*Trie
	prefix int // words passing through this node
	words  int // words ending exactly here
}

func (t *Trie) Insert(word string) {
	node := t
	for i := 0; i < len(word); i++ {
		c := word[i] - 'a'
		if node.next[c] == nil {
			node.next[c] = &Trie{}
		}
		node = node.next[c]
		node.prefix++
	}
	node.words++
}

func (t *Trie) walk(s string) *Trie {
	node := t
	for i := 0; i < len(s) && node != nil; i++ {
		node = node.next[s[i]-'a']
	}
	return node
}

func (t *Trie) CountWord(word string) int {
	if node := t.walk(word); node != nil {
		return node.words
	}
	return 0
}

func (t *Trie) CountPrefix(prefix string) int {
	if node := t.walk(prefix); node != nil {
		return node.prefix
	}
	return 0
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Preorder with null markers for serializationO(n) time · O(n) space

To store a tree as a string and rebuild it (serialization, comparing or de-duplicating subtree shapes): walk in preorder, write # for a missing child and separate with commas; rebuild by reading tokens back in the same preorder, returning null at each #. Preorder plus null markers pins the tree down uniquely. LC 297 (Serialize and Deserialize Binary Tree); a BST can drop the markers, as in LC 449.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def serialize(root) -> str:
    """Preorder with '#' for each missing child, comma-separated (LC 297)."""
    out = []

    def walk(node) -> None:
        if not node:
            out.append("#")
            return
        out.append(str(node.val))
        walk(node.left)
        walk(node.right)

    walk(root)
    return ",".join(out)


def deserialize(data: str):
    """The tree serialize() wrote: the tokens are read back in the same preorder."""
    tokens = iter(data.split(","))

    def build():
        t = next(tokens)
        if t == "#":
            return None
        node = TreeNode(int(t))
        node.left = build()  # left before right, as they were written
        node.right = build()
        return node

    return build()
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// Preorder with '#' for each missing child, comma-separated (LC 297).
string serialize(TreeNode* root) {
    if (!root) return "#";
    return to_string(root->val) + "," + serialize(root->left) + "," + serialize(root->right);
}

// The tree serialize() wrote: the tokens are read back in the same preorder.
TreeNode* deserialize(const string& data) {
    size_t pos = 0;
    function<TreeNode*()> build = [&]() -> TreeNode* {
        size_t end = data.find(',', pos);
        if (end == string::npos) end = data.size();
        string t = data.substr(pos, end - pos);
        pos = end + 1;
        if (t == "#") return nullptr;
        TreeNode* node = new TreeNode(stoi(t));
        node->left = build();  // left before right, as they were written
        node->right = build();
        return node;
    };
    return build();
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Codec {
    private String[] tokens;
    private int next;

    // Preorder with '#' for each missing child, comma-separated (LC 297).
    String serialize(TreeNode root) {
        if (root == null) return "#";
        return root.val + "," + serialize(root.left) + "," + serialize(root.right);
    }

    // The tree serialize() wrote: the tokens are read back in the same preorder.
    TreeNode deserialize(String data) {
        tokens = data.split(",");
        next = 0;
        return build();
    }

    private TreeNode build() {
        String t = tokens[next++];
        if (t.equals("#")) return null;
        TreeNode node = new TreeNode(Integer.parseInt(t));
        node.left = build(); // left before right, as they were written
        node.right = build();
        return node;
    }
}
Go
import (
	"strconv"
	"strings"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// serialize writes the tree in preorder with "#" for each missing child, comma-separated (LC 297).
func serialize(root *TreeNode) string {
	if root == nil {
		return "#"
	}
	return strconv.Itoa(root.Val) + "," + serialize(root.Left) + "," + serialize(root.Right)
}

// deserialize rebuilds the tree serialize wrote, reading the tokens back in the same preorder.
func deserialize(data string) *TreeNode {
	tokens := strings.Split(data, ",")
	next := 0
	var build func() *TreeNode
	build = func() *TreeNode {
		t := tokens[next]
		next++
		if t == "#" {
			return nil
		}
		v, _ := strconv.Atoi(t)
		node := &TreeNode{Val: v}
		node.Left = build() // left before right, as they were written
		node.Right = build()
		return node
	}
	return build()
}
DFS over a trie carrying the changes leftO(total length) build · O(26 × L²) worst-case query (with LC 211 "." wildcards a query can visit every node)

When a lookup is not exact but allows wildcards or exactly one changed letter (LC 676, Implement Magic Dictionary; LC 211 with "."): DFS over the trie, following the child for the current letter, and step into a different child only while the one change is unused. At the end of the word, require exactly one change to have been made.

Python
class MagicDictionary:
    """Does a word differ from some dictionary word in exactly one letter? (LC 676)"""

    def __init__(self, words: list[str]):
        self.root: dict = {}  # a trie of nested dicts; "$" marks the end of a word
        for w in words:
            node = self.root
            for ch in w:
                node = node.setdefault(ch, {})
            node["$"] = True

    def search(self, word: str) -> bool:
        def dfs(node: dict, i: int, changed: bool) -> bool:
            if i == len(word):
                return changed and "$" in node  # exactly one change, ending on a word
            for ch, child in node.items():
                if ch == "$":
                    continue
                if ch == word[i]:
                    if dfs(child, i + 1, changed):
                        return True
                elif not changed and dfs(child, i + 1, True):  # spend the one change here
                    return True
            return False

        return dfs(self.root, 0, False)
C++
// Does a word differ from some dictionary word in exactly one letter? (LC 676)
class MagicDictionary {
    struct Node {
        Node* next[26] = {};
        bool end = false;  // a dictionary word ends here
    };
    Node root;

    bool dfs(const Node* node, const string& word, size_t i, bool changed) const {
        if (i == word.size()) return changed && node->end;  // exactly one change, ending on a word
        for (int c = 0; c < 26; c++) {
            const Node* child = node->next[c];
            if (!child) continue;
            if (c == word[i] - 'a') {
                if (dfs(child, word, i + 1, changed)) return true;
            } else if (!changed && dfs(child, word, i + 1, true)) {  // spend the one change here
                return true;
            }
        }
        return false;
    }

public:
    explicit MagicDictionary(const vector<string>& words) {
        for (const string& w : words) {
            Node* node = &root;
            for (char ch : w) {
                if (!node->next[ch - 'a']) node->next[ch - 'a'] = new Node();
                node = node->next[ch - 'a'];
            }
            node->end = true;
        }
    }
    bool search(const string& word) const { return dfs(&root, word, 0, false); }
};
Java
// Does a word differ from some dictionary word in exactly one letter? (LC 676)
class MagicDictionary {
    private static class Node {
        final Node[] next = new Node[26];
        boolean end; // a dictionary word ends here
    }

    private final Node root = new Node();

    MagicDictionary(String[] words) {
        for (String w : words) {
            Node node = root;
            for (char ch : w.toCharArray()) {
                if (node.next[ch - 'a'] == null) node.next[ch - 'a'] = new Node();
                node = node.next[ch - 'a'];
            }
            node.end = true;
        }
    }

    boolean search(String word) {
        return dfs(root, word, 0, false);
    }

    private boolean dfs(Node node, String word, int i, boolean changed) {
        if (i == word.length()) return changed && node.end; // exactly one change, ending on a word
        for (int c = 0; c < 26; c++) {
            Node child = node.next[c];
            if (child == null) continue;
            if (c == word.charAt(i) - 'a') {
                if (dfs(child, word, i + 1, changed)) return true;
            } else if (!changed && dfs(child, word, i + 1, true)) { // spend the one change here
                return true;
            }
        }
        return false;
    }
}
Go
type trieNode struct {
	next [26]*trieNode
	end  bool // a dictionary word ends here
}

// MagicDictionary answers whether a word differs from some dictionary word in exactly one letter (LC 676).
type MagicDictionary struct {
	root *trieNode
}

func NewMagicDictionary(words []string) *MagicDictionary {
	root := &trieNode{}
	for _, w := range words {
		node := root
		for i := 0; i < len(w); i++ {
			c := w[i] - 'a'
			if node.next[c] == nil {
				node.next[c] = &trieNode{}
			}
			node = node.next[c]
		}
		node.end = true
	}
	return &MagicDictionary{root}
}

func (d *MagicDictionary) Search(word string) bool {
	var dfs func(node *trieNode, i int, changed bool) bool
	dfs = func(node *trieNode, i int, changed bool) bool {
		if i == len(word) {
			return changed && node.end // exactly one change, ending on a word
		}
		for c, child := range node.next {
			if child == nil {
				continue
			}
			if byte(c) == word[i]-'a' {
				if dfs(child, i+1, changed) {
					return true
				}
			} else if !changed && dfs(child, i+1, true) { // spend the one change here
				return true
			}
		}
		return false
	}
	return dfs(d.root, 0, false)
}

Why it works

  1. Every trie node corresponds to exactly one prefix, the path from the root to it, so looking up a prefix walks L steps regardless of how many words are stored.
  2. Counts on nodes (words passing through, words ending here) are incremented along the path on insert, so the number of words with a given prefix is simply the count on its last node.
  3. A preorder sequence with null markers determines a binary tree uniquely: deserializing reads it back in the same order, returning at each null marker, so every value and every empty slot is consumed exactly once.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
字典树的每个节点代表一个前缀,插入和查找都是一个字符一个字符往下走,复杂度只和单词长度有关。节点上可以存经过的单词数和在此结束的单词数,这样前缀计数和删除都是 O(L)。二叉树序列化我用先序遍历,空节点写成一个特殊标记,比如井号,因为带空标记的先序能唯一确定一棵树。反序列化按同样的顺序读回来,遇到标记就返回空。
English
In a trie each node stands for one prefix, and insert and lookup walk down one character at a time, so the cost depends only on the word length. Nodes can store how many words pass through and how many end there, which makes prefix counts and deletion O(L). To serialize a binary tree I write a preorder walk with a marker such as a hash sign for empty children, because preorder with null markers pins down the tree uniquely. Deserializing reads the tokens back in the same order and returns an empty child at each marker.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. A trie holds N words. Checking whether a word of length L is present takes:
  2. Why does preorder with explicit null markers (such as #) let a binary tree be rebuilt, while plain preorder does not?
  3. Building a trie from a list of words takes what time?
    def build(words):
        root = {}
        for w in words:
            node = root
            for ch in w:
                node = node.setdefault(ch, {})
            node['$'] = True
        return root

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class Trie:
    def __init__(self):
        self.children: dict[str, Trie] = {}
        self.prefix = 0
        self.words = 0

    def insert(self, word: str) -> None:
        node = self
        for ch in word:
        return node.words if node else 0

    def count_prefix(self, prefix: str) -> int:
        node = self._walk(prefix)
        return node.prefix if node else 0

Practice by stage

This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 3

#ProblemApproachRating
676Implement Magic DictionaryDesign dictionary queries allowing exactly one character change, distinguishing exact matches from valid approximate matches.
1166Design File System 🔒Implement path creation and retrieval, checking parent existence, duplicate creation, and root-directory semantics.Rating 1479
297Serialize and Deserialize Binary TreeDesign a reversible tree encoding that preserves missing children, verifying structure and values through serialization round trips.

Advanced 3

#ProblemApproachRating
745Prefix and Suffix SearchPrebuild an index for combined prefix and suffix queries and analyze trie or composite-key tradeoffs in query time and space.
588Design In-Memory File System 🔒Design directory-tree and file-content interfaces, distinguishing files from directories and keeping directory listings sorted.
449Serialize and Deserialize BSTUse BST value bounds to reduce encoding redundancy and explain the ordering constraints needed to reconstruct the structure.

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.