Garden Centre Plant Finder

MediumtrieAlso known as Search Suggestions System

A garden centre kiosk suggests plants as a customer types: after each letter it shows up to three plant names starting with the letters so far, in alphabetical order. The catalogue merges several suppliers, so a name can be listed more than once, but the kiosk never shows a name twice in one set of suggestions.

Your task

Write suggestPlants(catalogue, typed). For each i from 1 to typed.length, take the first i letters of typed and find the distinct catalogue names that start with them. Return a list with one entry per letter typed: the alphabetically first three of those names, or fewer if fewer exist, or an empty list if none do.

A name that equals the typed letters exactly counts as starting with them.

suggestPlants(catalogue: string[], typed: string) → string[][]

Examples

Example 1
Input
catalogue = ["mint", "marigold", "maple", "moss", "magnolia", "lavender"]
typed = "map"
Output
[["magnolia", "maple", "marigold"], ["magnolia", "maple", "marigold"], ["maple"]]
Why

After "m", five names match, and the first three alphabetically are magnolia, maple and marigold. After "ma", the same three are suggested, because mint and moss no longer match. After "map", only maple matches.

Example 2
Input
catalogue = ["fern", "fig", "fern", "fuchsia"]
typed = "fex"
Output
[["fern", "fig", "fuchsia"], ["fern"], []]
Why

fern is listed twice but shown once. After "f" the suggestions are fern, fig and fuchsia. After "fe" only fern matches, and after "fex" nothing matches.

Constraints

  • 1 ≤ catalogue.length ≤ 1,000
  • 1 ≤ typed.length ≤ 30, and every name is 1 to 30 letters long
  • Only lowercase letters a to z.
Start with brute force

For each prefix of typed, scan the whole catalogue, keep the matches, remove duplicates, sort and take three. That is O(L · n log n) for L typed letters and n names, and the work is repeated from scratch for every keystroke. A kiosk should spend the same small amount of work on each keystroke regardless of the catalogue size.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code