Garden Centre Plant Finder

MediumtrieAlso known as Search Suggestions System

A garden centre has a touch-screen kiosk where customers look up plants. As a customer types, letter by letter, the screen shows up to three plant names that start with what they have typed so far, in alphabetical order, so they can tap one instead of finishing the word.

The catalogue comes from several suppliers, so the same plant name can be listed more than once. The kiosk should never show the same 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 start with m; the first three alphabetically are magnolia, maple, marigold. After "ma": magnolia, maple, marigold again (mint and moss drop out). After "map": only maple.

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": fern, fig, fuchsia. After "fe": fern. After "fex": nothing starts with it, so an empty list.

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 names that start with it, remove duplicates, sort, and take three.

That is O(L · n log n) for L typed letters and n names, and every keystroke repeats the scan from scratch. On a kiosk with a large catalogue, each keystroke should cost about the same small amount, whatever 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