Prefix Matcher
DatadogMedium
Implement the class PrefixMatcher. add(prefix) stores a prefix, and match(strings) reports which of the given strings begin with at least one stored prefix.
Part 1: Match strings against stored prefixes
Implement the class PrefixMatcher:
add(prefix)storesprefix. Adding the same prefix again changes nothing.match(strings)returns the strings fromstringsthat begin with at least one stored prefix, keeping the order ofstrings. A string identical to a stored prefix matches. A string that begins with several stored prefixes appears once in the result. If the same string occurs twice instringsand matches, it appears twice. An empty string never matches, since every stored prefix is non-empty.
match only reads the prefixes stored so far; prefixes added later never affect an earlier call.
The matcher can hold many prefixes and match can be called many times. A call to match must not compare every string against every stored prefix: its work must stay proportional to the total length of the strings in the call plus the prefixes stored so far.
- Example 1
- init
[]- operations
[["add",["ab"]],["add",["xyz"]],["match",[["abc","xy","xyzzy","ba","ab"]]]]- Output
[null,null,["abc","xyzzy","ab"]]
Why:
abcandabbegin withab, andxyzzybegins withxyz.xyis shorter thanxyz, so it does not match, andbadoes not begin withab.
Constraints
1 <= len(prefix)'a' <= prefix[i] <= 'z'strings[i]consists only of lowercase English letters and may be empty0 <= len(strings)- The total length of all prefixes and all strings across all calls is at most
100000
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.