← All Exercises

Trie Autocomplete with Prefix Suggestions

intermediatetypescript~25min

Background

Tries back search-as-you-type boxes, IP routing tables, and spell checkers with prefix-based lookup.

Problem

Implement a trie that inserts words and returns the first k dictionary words starting with a given prefix, ordered lexicographically.

Input

An array of lowercase words, a prefix string, and a positive limit k.

Output

Up to k matching words in lexicographic order, or an empty array when the prefix has no completion.

Sample tests

Sample 1

Input: words = ["car","card","care","dog"], prefix = "car", limit = 2
Expected: ["car","card"]

Sample 2

Input: words = ["apple","app","apply"], prefix = "app", limit = 3
Expected: ["app","apple","apply"]

Sample 3

Input: words = ["dog"], prefix = "cat", limit = 5
Expected: []

Your solution

Learning objective

Combine trie traversal with an ordered DFS and early stopping to implement prefix search.