Binary search · Medium
An autocomplete BFF returns up to three lexicographically first product names for each prefix typed by a user.
Return suggestions after each added character.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ products:string[], query:string }
Input rules
- Products and query contain lowercase ASCII letters; duplicate products identify one suggestion.
What each field means
products— lowercase product names; repeated names represent one suggestion.query— text typed one character at a time.
Output
Return value and rules
- Return one suggestion array for each nonempty prefix of
query. - For each prefix, return up to three distinct matching names in ASCII order.
- A prefix with no matches gets
[]; an empty query gets no suggestion arrays.
Constraints
- 0 <= products.length <= 50000; total product characters <= 500000
- 0 <= query.length <= 1000; each product is nonempty and at most 80 characters.
Examples
Example 1
{
"products": [
"mouse",
"mobile",
"moneypot",
"monitor",
"mousepad"
],
"query": "mo"
}Returns
[
[
"mobile",
"moneypot",
"monitor"
],
[
"mobile",
"moneypot",
"monitor"
]
]Example 2
{
"products": [],
"query": "a"
}Returns
[
[]
]Required complexity
O(N log N × L + query.length × (log N × L + L)) time and O(total input characters) space