Suffix Count
Solve an easy problem for finding the count of words with a suffix.
Problem statement
A suffix is a letter or a contiguous group of letters present at the end of a string. Given an array of strings words
and a string suff
, return the number of strings in words
that contain suff
as a suffix.
Example 1
Sample Input
words: ["paid", "said", "maid", "raid", "apple", "maple", "staple"]suff: "id"
Sample output
4
Explanation
The four strings, "paid"
, "said"
, "maid"
and "raid"
contain "id"
as a suffix.
Example 2
Sample Input
words: ["paid", "said", "maid", "raid", "apple", "maple", "staple"]suff: "ple"
Sample output
3
Explanation
The three strings, "apple"
, "maple"
and "staple"
, contain "ple"
as a suffix.
Try it yourself
Try to solve the problem yourself before reading the solution.
#include <iostream>#include <vector>using namespace std;int suffixCount(vector<string>& words, string suff) {// your code goes herereturn -1;}
Intuition
The problem can be rephrased as counting the number of words in a list with a given suffix. A naive solution would be to traverse through all the words in the given list and check if the word has suff
as the suffix.
// returns the count of words in the list, which have suff as a suffixint suffixCount(words, suff){count = 0for every word in words list//check if suff is a suffix of wordif isSuffix(suff, word) is truecount+1return count}// checks if suff is a suffix of wordboolean isSuffix(suff, word){for char at index i the reversed (suff) and in the reversed (word)if character at index in suff, equals to the character at index in wordcontinueelsebreakif the value of index equals the length of suffreturn true}
To check if suff
is a suffix of a word, we traverse and compare all characters of both the word and suff
simultaneously. This operation adds a time complexity of suff
. This comparison operation is performed for all the