AlgoFrames

Starts-with

Warm-up · Write code · about 10 min

Given a list of words and a prefix, return how many words start with prefix. A word that appears twice counts twice.

Store a count in every node: the number of words that pass through it.

Example 1

Input:

[["apple","app","apt","bat"],"ap"]

Output:

3

apple, app and apt start with ap.

Example 2

Input:

[["apple","bat"],"cat"]

Output:

0

No edge c from the root, so the answer is 0.

Constraints

  • 0 ≤ words.length ≤ 2,000
  • Each word has 1 to 12 lowercase letters
  • 1 ≤ prefix.length ≤ 12

Learn the idea first: Tries: insert, search, prefix, a visual lesson.

More Tries: insert, search, prefix problems