Autocomplete System

Algorithm Trie Autocomplete

Design and implement an autocomplete system. The system should be initialized with a list of words (e.g., product names or dictionary words). As a user types a query string character by character, the system should return up to three suggested words from the original list that start with the current query prefix, sorted in lexicographical order.

Requirements:

  • Create a function that accepts the initial list of words.
  • Implement a method that, given a query string, returns an array of arrays. Each sub-array represents the autocomplete suggestions after the user types each character of the query.
  • For each state of the query, if there are fewer than three valid suggestions, return all available suggestions. If no word matches the current prefix, return an empty array for that state.
  • Optimize the solution for efficient lookup as the list of words can be large.

Example:

Assume the initial word list is: ["apple", "app", "apricot", "banana", "bat", "bath", "batman"]

For the query string: "ba"

The function should return:

[
["banana", "bat", "bath"], // suggestions after 'b'
["banana", "bat", "bath"] // suggestions after 'ba'
]

Develop a solution in the programming language of your choice and ensure that your code handles edge cases effectively.


Loading...