![]() |
VOOZH | about |
Given an array of strings arr[] and some queries where each query consists of a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str.
Examples:
Input: arr[] = ["abba", "abbb", "abbc", "abbd", "abaa", "abca"], str = "abbg", k = 3
Output: 4
"abba", "abbb", "abbc" and "abbd" are the matching strings.Input: arr[] = ["geeks", "geeksforgeeks", "forgeeks"], str = "geeks", k = 2
Output: 2
Table of Content
We compare the first
kcharacters of the given string with the firstkcharacters of every string in the array. If they match, we count that string.
4
We use a Trie to store all strings and maintain frequency at each node. While inserting, we increment the frequency for every prefix. Then for a given string, we traverse up to length
kand return the frequency stored at that node, which represents how many strings share that prefix.
k is reached, return stored frequency4