DSA Factory
Free Tries lessonsTries · Stage 1 · Prefix questions · Step 4

Distinct prefixes

Count every node the trie actually needed to create, which is the number of distinct prefixes overall. About 8 minutes.

Counting creations, not steps

Insert every word as usual, but keep a counter that only goes up when a brand-new node has to be made. Walking into a node that already exists, because an earlier word passed through it, doesn't count again: that beginning was already known.

It is like counting the distinct roads on a map rather than the trips taken along them.

New node: a prefix nobody has reached before: count it.
Existing node: some earlier word already has this prefix: don't count it again.
In code
count = 0
if c not in node:
    node[c] = {}
    count += 1      # a new prefix
words = [cat, car] · count only nodes that get created
•catr
created
0

An empty trie: just the root, which isn't a prefix.

Move 1 of 4

What this number means

This count is exactly the number of nodes in the finished trie, other than the root. It measures how much the words actually overlap.

A list of totally different words needs almost one node per letter. A list of words sharing long beginnings needs far fewer, because the shared roads are built only once.

Overlap shows up as savings: shared prefixes mean fewer new nodes overall.
Quick check

words = ["cat", "car"]. How many distinct prefixes are there?

  1. A4
  2. B6
Show the answer

4. "c", "ca" are shared; "cat" and "car" each add one more distinct prefix: 4 in total.

Your problem

Distinct prefixes

words is a list of lowercase words. Return how many distinct, non-empty prefixes exist across all of words combined (a prefix shared by several words is counted once).

Example
words = ["cat", "car"] → 4

0 ≤ words.length ≤ 1,000 · 1 ≤ words[i].length ≤ 30 · every word is lowercase a-z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve