Skip to main content
Back to problems
#1268
Medium Algorithms

Search suggestions system

Array String Binary Search Trie Sorting Heap (Priority Queue)
65.1% acceptance
Feb 25, 2026
5113
266
You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn suggested_products(mut products: Vec<String>, search_word: String) -> Vec<Vec<String>> {
    products.sort();
    let mut result = Vec::new();
    let sw = search_word.as_bytes();

    for i in 1..=sw.len() {
      let prefix = &search_word[..i];
      let mut suggestions = Vec::new();
      for p in &products {
        if p.starts_with(prefix) {
          suggestions.push(p.clone());
          if suggestions.len() == 3 { break; }
        }
      }
      result.push(suggestions);
    }
    result
  }
}