AlgoMaster Logo

Search Suggestions System

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with Sorting

Intuition:

The simplest solution to this problem is to sort the list of products first. For every typed prefix, we can iterate through all the products and check if a product starts with this prefix. If it does, we add it to our result list for that prefix until we have added 3 suggestions or exhausted the list.

Steps:

  1. Sort the products array.
  2. For each prefix formed by typing the search word character by character:
    • Initialize an empty list to store suggestions.
    • Iterate through the sorted products list and check if the product starts with the current prefix.
    • Add the product to the suggestions list and stop if we gather 3 suggestions.
  3. Append the list of suggestions for each prefix to the result.

Code:

2. Prefix Trie with DFS

Intuition:

We can use a Trie to represent all product names efficiently. For each character typed, we traverse the Trie to find the node representing that prefix and perform a DFS to gather the top 3 lexicographical suggestions.

Steps:

  1. Build a Trie with all product names.
  2. For each character typed:
    • Traverse the Trie to find the node representing the current prefix.
    • Perform a DFS from this node to collect up to 3 product suggestions.

Code:

Intuition:

This approach utilizes binary search to find the starting point of the valid suggestions in the sorted products array. The addition of two pointers helps in efficiently reducing the search space as we progress through each character in the search word.

Steps:

  1. Sort the products array.
  2. Use binary search to efficiently find the starting index of products matching the current prefix.
  3. Use two pointers to narrow down the range of possible suggestions for each new character typed.

Code: