<AI/>
enru
Все статьи

Search suggestions system

LeetCode 1268: Suggest up to three products for every prefix of a search word using a trie or binary search over a sorted array.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#trie#binary search
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an array of strings products with the available product names and a string searchWord that the user is typing.

Implement a function that returns an array of arrays, where:

  • Each subarray contains the list of suggestions for the corresponding prefix of searchWord. The first subarray corresponds to the prefix made of the first character of searchWord, the second one to the prefix made of the first two characters, and so on.
  • Each subarray contains up to three products from products, sorted lexicographically.
  • If no matches are found for a prefix, the corresponding subarray must be empty.

Constraints

  • 1 <= products.length <= 1000: the number of products.
  • 1 <= products[i].length <= 3000: the length of each product name.
  • 1 <= searchWord.length <= 1000: the length of the search word.
  • All strings consist only of lowercase English letters.

Examples

Products: products = ["mobile","mouse","moneypot","monitor","mousepad"]

Search word: searchWord = "mouse"

Answer:

[
  ["mobile","moneypot","monitor"], // suggestions for the prefix "m"
  ["mobile","moneypot","monitor"], // suggestions for the prefix "mo"
  ["mouse","mousepad"],            // suggestions for the prefix "mou"
  ["mouse","mousepad"],            // suggestions for the prefix "mous"
  ["mouse","mousepad"],            // suggestions for the prefix "mouse"
]

Trie approach

Problems that require finding strings by a given prefix are usually a perfect fit for a data structure called a prefix tree (Trie).

We need to implement the data structure itself and a method that returns the complete words starting with a given prefix. To speed up the search and avoid sorting at query time, besides the hash table of child nodes each node can store a sorted list of keys. This list is built or updated when new words are added.

So the solution has two steps:

  • Convert the input array products into a prefix tree.
  • Walk through searchWord character by character, extracting suggestions for each prefix.
typescript
class Trie {
  word: string = '';
  sort: string[] = [];
  children: Map<string, Trie> = new Map();
 
  insert(word: string): void {
    this._insert(word, [...word]);
  }
 
  private _insert(origin: string, word: string[]): void {
    if (word.length === 0) {
      this.word = origin;
      return;
    }
 
    const char = word[0];
    let child = this.children.get(char);
 
    if (!child) {
      child = new Trie();
      this.children.set(char, child);
      this.sort.push(char);
    }
 
    child._insert(origin, word.slice(1));
  }
 
  closest(prefix: string[], count: number): string[][] {
    const res: string[][] = [];
    let excludeChar: string | null = null;
 
    if (prefix.length > 0) {
      excludeChar = prefix[0];
    }
 
    res.push(this.exactWords(excludeChar, count));
 
    if (prefix.length === 0) {
      return res;
    }
 
    const child = this.children.get(prefix[0]);
    if (!child) {
      res[0] = this.exactWords(null, count);
      return res.concat(this.gd(prefix));
    }
 
    return res.concat(child.closest(prefix.slice(1), count));
  }
 
  private exactWords(excludeChar: string | null, n: number): string[] {
    let res: string[] = [];
    if (this.word.length > 0) {
      res.push(this.word);
      n--;
    }
 
    if (n === 0) {
      return res;
    }
 
    for (const childChar of this.sort) {
      if (excludeChar !== null && childChar === excludeChar) {
        continue;
      }
 
      const childWords = this.children.get(childChar)!.exactWords(null, n);
      if (childWords.length >= n) {
        return res.concat(childWords.slice(0, n));
      }
 
      res = res.concat(childWords);
      n -= childWords.length;
 
      if (n === 0) {
        break;
      }
    }
 
    return res;
  }
 
  gd(prefix: string[]): string[][] {
    const res: string[][] = [];
    for (let i = 0; i < prefix.length; i++) {
      res.push([]);
    }
    return res;
  }
}
 
export function suggestedProductsTrie(products: string[], searchWord: string): string[][] {
  const root = new Trie();
 
  products.sort();
 
  for (const p of products) {
    root.insert(p);
  }
 
  const runeSearch = [...searchWord];
  const firstChar = runeSearch[0];
  const worldStart = root.children.get(firstChar);
 
  if (!worldStart) {
    return root.gd(runeSearch);
  }
 
  const suggestions = worldStart.closest(runeSearch.slice(1), 3);
  const res: string[][] = new Array(suggestions.length);
  let prev: string[] = [];
  let i = suggestions.length - 1;
 
  if (i >= 0) {
    prev = suggestions[i].slice();
    res[i] = prev;
    i--;
  }
 
  for (; i >= 0; i--) {
    let newItem = suggestions[i].slice();
 
    if (prev.length === 0) {
      res[i] = newItem;
      prev = newItem.slice();
      continue;
    } else if (newItem.length === 0) {
      res[i] = prev.slice();
      continue;
    }
 
    newItem = newItem.concat(prev);
    newItem.sort();
 
    if (newItem.length > 3) {
      newItem = newItem.slice(0, 3);
    }
 
    res[i] = newItem;
    prev = newItem.slice();
  }
 
  return res;
}

Complexity Analysis

Time Complexity

Building the prefix tree

  • Adding a word of length m to the tree takes O(m) operations.
  • So for an array of n words the total time is O(m * n), where m is the length of the longest word in products and n is the number of words.

Looking up suggestions by prefix

  • Looking up the suggestions for a prefix can be estimated as O(m), where m is the length of the longest word in products
  • Since searchWord has length s, we need to look up suggestions for each of its s prefixes. In total, the lookups take O(s * m).

Overall complexity

The complexity of the whole algorithm is O(m * n + s * m), where:

  • m is the length of the longest word in products,
  • n is the number of words in products,
  • s is the length of searchWord.

Space Complexity

We need memory for the prefix tree. In the worst case it's O(m * n), where m is the length of the longest word in products and n is the length of products.

Possible trie optimizations

Avoiding redundant depth-first searches

The first thing that stands out is that for every prefix we have to go all the way down the tree to the leaves. This duplicates work, since the suggestion lists are identical for many prefixes. It's especially noticeable for long prefixes, where the variety of suggestions is much lower than for short ones.

To avoid this, we can change the approach: instead of starting with the shortest prefix and moving down, we start with the longest prefix and move up the tree. Words then "bubble up" from lower nodes to higher ones, and we only need to go down when the higher node has more variety in its children than the current one.

While this optimization can improve real-world performance, it doesn't change the asymptotic complexity of the algorithm.

Trading memory for speed

In real life, memory is usually cheaper than CPU time, and reads happen much more often than writes. Moreover, product catalogs are usually not that large. Given that, we can significantly optimize the solution by modifying the prefix tree.

We can store in each node an additional suggestions array with references to the final products returned as suggestions. This avoids the depth-first search when extracting suggestions and reduces the complexity from O(s * m) to O(s), where s is the length of searchWord. In practice this can greatly improve performance by using cheap memory.

However, this modification affects the cost of inserting a word into the tree. Insertion now takes O(m * n * m), since for every affected node we need to recompute the suggestions array when adding a new word, going down the tree.

In the context of this problem, where read and write loads are not distinguished, this optimization actually makes things worse. The increased insertion cost can outweigh the benefits, especially with a large number of writes.

Binary search approach

What's special about this problem is that converting the input array into another data structure can be seen as a write load, and searching as a read load. Within this problem, writes significantly outweigh reads, which is unusual for classic search systems.

To get the best result, we should modify the input array as little as possible. If we sort products, all suggestions for a given prefix end up next to each other. This simplifies finding suggestions for a prefix:

  • Find the index of the first word in the sorted array that starts with the given prefix.
  • Check the two words after it to see whether they also match the prefix.

To find the first word with the given prefix, we can use a modified binary search that efficiently locates the starting position of the prefix in the sorted array.

This approach keeps changes to the input array to a minimum while maintaining good search performance thanks to sorting and binary search.

This implementation can be optimized further:

  • In a sorted array, the suggestions for the next prefix are guaranteed to be either in the same range as for the current prefix or to the right of it. So we can narrow the binary search down to start from the previous range instead of searching the whole array.
  • The linear backward scan used to find the first word starting with the prefix can be eliminated by modifying the binary search so that it returns the index of the first matching element right away.
typescript
export const suggestedProducts = (products: string[], searchWord: string): string[][] => {
  products.sort();
  let res: string[][] = [];
  let items = products;
 
  for (let idx = 0; idx < searchWord.length; idx++) {
    const prefix = searchWord.substring(0, idx + 1);
    items = suggestions(items, prefix);
 
    if (items.length === 0) {
      break;
    }
 
    const maxLen = Math.min(3, items.length);
    res.push(items.slice(0, maxLen));
  }
 
  res = gd(res, searchWord.length - res.length);
 
  return res;
};
 
export const suggestions = (products: string[], prefix: string): string[] => {
  const startIdx = findFirstProductWithPrefix(products, prefix);
 
  if (startIdx === -1) {
    return [];
  }
 
  const res: string[] = [];
 
  for (let i = startIdx; i < products.length; i++) {
    if (!products[i].startsWith(prefix)) {
      break;
    }
    res.push(products[i]);
  }
 
  return res;
};
 
export const findFirstProductWithPrefix = (products: string[], prefix: string): number => {
  let left = 0;
  let right = products.length - 1;
  let res = -1;
 
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
 
    if (products[mid].startsWith(prefix)) {
      res = mid;
      right = mid - 1; // Look for the earliest occurrence
    } else if (products[mid] < prefix) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
 
  return res;
};
 
export const gd = (res: string[][], tailLength: number): string[][] => {
  for (let i = 0; i < tailLength; i++) {
    res.push([]);
  }
  return res;
};

Complexity Analysis

Time Complexity

We first sort the input array, which takes O(m * n log n) string comparisons, and then perform s binary searches, which take O(s * m * log n). Here n is the length of products, m is the length of the longest word, and s is the length of searchWord.

Space Complexity

Apart from the memory used by sorting and the result itself, this implementation needs constant extra memory: O(1).