24. Prefix Match with Other Strings
The problem can be found at the following link: Question Link
My Approach
To solve the problem, I have used the following approach:
Check if the length of the prefix substring (
k
) is greater than the length of the given matching string (str
). If it is, return 0 since no prefix matches are possible.Extract the prefix substring (
toSearch
) of lengthk
from the given matching stringstr
.Initialize a counter
c
to keep track of the number of strings in the arrayarr
that have a matching prefix.Iterate through each string in the array
arr
. If the substring of lengthk
from each string matches thetoSearch
string, increment the counterc
.Finally, return the value of the counter
c
.
Time and Auxiliary Space Complexity
Time Complexity:
O(n * k)
, where n is the number of strings in the arrayarr
andk
is the length of the prefix substring. We iterate through each string in the array and compare the substrings of lengthk
with thetoSearch
string.Auxiliary Space Complexity:
O(1)
as we are not using any extra space that scales with the input.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated