Garden Centre Plant Finder
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
catalogue = ["mint", "marigold", "maple", "moss", "magnolia", "lavender"] typed = "map"
[["magnolia", "maple", "marigold"], ["magnolia", "maple", "marigold"], ["maple"]]
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.
catalogue = ["fern", "fig", "fern", "fuchsia"] typed = "fex"
[["fern", "fig", "fuchsia"], ["fern"], []]
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- Hint 1
Compare the suggestions for "m" and "ma" in the first example. Can a name not starting with "m" ever appear for "ma"? What does each extra letter do to the candidates?
- Hint 2
Each letter can only narrow the candidates. In a sorted catalogue, where do all the names starting with "ma" sit relative to each other?
- Hint 3
Names sharing a beginning share a path in a trie. Could each trie node remember the answer for its own prefix?
- Hint 4
Sort the catalogue and drop duplicates. Insert the names into a trie in that order, and at every node you pass, append the name if the node's list has fewer than 3 entries. Then walk
typedletter by letter, reading each node's list. Once a letter has no child, every later answer is an empty list.
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.
How to solve it
Every prefix of typed is a node in a trie of the catalogue. If each node already knows its three alphabetically first names, a keystroke is one step down plus a read.
To fill those lists, insert the names in alphabetical order. The first three names through a node are then its three smallest, so each node keeps the first three it sees.
Trace the first example. Sorted, the names are lavender, magnolia, maple, marigold, mint and moss.
- lavender creates the l branch. magnolia passes through m and ma, so both of those lists get magnolia.
- maple passes through m, ma and map, so m and ma now hold magnolia and maple, and map holds maple.
- marigold passes through m and ma, which fills both lists with three names.
- mint and moss pass through m, whose list is already full, so they are not added there.
- When "map" is typed, the list at m is magnolia, maple and marigold, the list at ma is the same, and the list at map is maple.
Removing duplicates first means a name never fills two slots. Once a letter has no child in the trie, the walk has left the trie for good, so every later letter gets an empty list.
You can also skip the trie and use the sorted list from hint 2. Names with the same prefix sit together, so you binary search for the first name that is at least the prefix and check up to three names from there. That costs O(log n · S) per keystroke instead of O(1), and it needs no extra data structure.
function suggestPlants(catalogue, typed) {
const names = [...new Set(catalogue)].sort(); // distinct, alphabetical
const root = { kids: new Map(), top: [] };
for (const name of names) {
let node = root;
for (const ch of name) {
if (!node.kids.has(ch)) node.kids.set(ch, { kids: new Map(), top: [] });
node = node.kids.get(ch);
// names arrive in order, so the first 3 to pass are the answer
if (node.top.length < 3) node.top.push(name);
}
}
const result = [];
let node = root;
for (const ch of typed) {
node = node ? node.kids.get(ch) : undefined;
result.push(node ? node.top : []);
}
return result;
}def suggest_plants(catalogue, typed):
names = sorted(set(catalogue)) # distinct, alphabetical
root = {"kids": {}, "top": []}
for name in names:
node = root
for ch in name:
node = node["kids"].setdefault(ch, {"kids": {}, "top": []})
# names arrive in order, so the first 3 to pass are the answer
if len(node["top"]) < 3:
node["top"].append(name)
result = []
node = root
for ch in typed:
node = node["kids"].get(ch) if node else None
result.append(node["top"] if node else [])
return resultRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.