Prefix Count

Solve an easy problem of counting prefixes of strings using tries.

Problem statement

A prefix of a string is any leading contiguous substring of the string. Given an array of strings words and a string pref, return the number of strings in words that contain pref as a prefix. A prefix of a string is any leading contiguous substring of the string.

Example 1

Sample input

words: ["pay", "paid", "pat", "app", "apple", "apply", "ape"]
pref: "pa"

Sample output

3

Explanation

There are three strings in the list of words that contain "pa" as a prefix, i.e. "pay", "paid"
and "pat".

Example 2

Sample Input

words: [“pay”, “paid”, “pat”, “app”, “apple”, “apply”, “ape”]
pref: "ap"

Sample output

4

Explanation

There are four strings "app", "apple", "apply", and "ape" that contain "ap" as a prefix.

Try it yourself

Please try to solve the problem yourself before reading the solution.

#include <iostream>
#include <vector>
using namespace std;
int prefixCount(vector<string>& words, string prefix) {
// your code goes here
return -1;
}
Solve prefix count in C++

Intuition

The problem can be rephrased as counting the number of words in a list with a given prefix. A naive solution would be to traverse through all the words in the given list and check if the word has pref as the prefix.

// returns the count of words in the list, which have pref as a prefix
int prefixCount(words, pref)
{
count = 0
for every word in words list
//check if pref is a prefix of word
if isPrefix(pref, word) is true
count+1
return count
}
// checks if pref is a prefix of word
boolean isPrefix(pref, word)
{
for char at index i the pref and in the word
if character at index in pref, equals to the character at index in word
continue
else
break
if the value of index equals the length of pref
return true
}
Pseudocode for brute-force approach

To check if pref is a prefix of a word, we traverse and compare all characters of both the word and pref simultaneously. This operation adds a time complexity of O(W)O(W), where WW ...

Access this course and 1400+ top-rated courses and projects.