Count Prefixes of a Given String

Easy · Tries · Array · String · Trie

Problem

You are given an array of strings words and a string s, all made of lowercase English letters.

Return how many strings in words are a prefix of s. A prefix is a substring that starts at the first character of s; s is a prefix of itself. Duplicate entries in words are counted separately.

Examples

Input: words = ["p","pl","plan","plane","an"], s = "plant"
Output: 3

"p", "pl" and "plan" start "plant"; "plane" does not, and "an" is inside "plant" but not at its start.

Input: words = ["x","x"], s = "xy"
Output: 2

Both copies of "x" count.

Input: words = ["longer"], s = "long"
Output: 0

A word longer than s cannot be its prefix.

Constraints

Approaches

Follow-up

Here the words are prefixes of s. The use cases turn the question around (how many words have s as their prefix, which needs a count on every trie node) and ask for the longest word that starts s instead of the count.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…