Browse curriculum

Search Suggestions System (LeetCode 1268)

Search Suggestions System (LeetCode 1268): after each letter typed, suggest up to three products that start with the prefix, smallest first. Sort the products, then binary search each prefix and take up to three matches from there.

Problem Understanding

Search Suggestions System (LeetCode 1268): given an array of products and a searchWord, after each character of searchWord is typed, suggest at most three products that start with the typed prefix. If more than three match, return the three lexicographically smallest. Return the list of suggestion lists.

Example: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" → [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]].

The Intuition: Matches Sit Together in Sorted Order

Sort the products and every prefix’s matches line up in one block. Finding the block is a lower-bound binary search.

  1. Sort the products once.
  2. For each typed prefix, binary search the first index whose product is >= prefix.
  3. Take up to three products from that index that still start with the prefix. Stop at the first one that does not: the block has ended.

The search is the lower bound from Search Insert Position, with strings in place of numbers. For the trie version of the idea, see Implement Trie (Prefix Tree).

Search Suggestions System Visualization

BOLD = MATCHES THE TYPED PREFIX · GREY = SORTS BEFORE IT · GREEN = SUGGESTED

SORT THE PRODUCTS

0

mobile

1

moneypot

2

monitor

3

mouse

4

mousepad

typed

:

lists

0 / 5

suggestions so far

None yet

 

Sort the products: mobile, moneypot, monitor, mouse, mousepad. Products sharing a prefix now sit together

Next

Typed "m": binary search the first product >= "m" in [0, 5)

Free preview: the first 9 of 27 steps

products

searchWord

Each row is a product in sorted order, with the letters matching the typed prefix in bold. lo, hi and mid sit in the margin, and rows left of lo, which sort before the prefix, turn grey. When the search ends, the suggestions turn green and are added on the right. Try Example 3 and No match, where a prefix has no products.

Search Suggestions System Dry Run

Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse". Sorted: mobile, moneypot, monitor, mouse, mousepad.

Typed Probes (mid) First index >= prefix Suggestions
m 2, 1, 0 0 mobile, moneypot, monitor
mo 2, 1, 0 0 mobile, moneypot, monitor
mou 2 (monitor < mou), 4, 3 3 mouse, mousepad
mous 2, 4, 3 3 mouse, mousepad
mouse 2, 4, 3 3 mouse, mousepad

Answer: the five lists above.

Search Suggestions System LeetCode Solution

One sort, then a lower-bound search and a short scan for each prefix.

Search Suggestions System Code
1var suggestedProducts = function(products, searchWord) {
2 products.sort();
3 const result = [];
4 let prefix = '';
5 for (const ch of searchWord) {
6 prefix += ch;
7 let lo = 0, hi = products.length;
8 while (lo < hi) {
9 const mid = (lo + hi) >> 1;
10 if (products[mid] >= prefix) {
11 hi = mid;
12 } else {
13 lo = mid + 1;
14 }
15 }
16 result.push(products.slice(lo, lo + 3).filter((p) => p.startsWith(prefix)));
17 }
18 return result;
19};

Search Suggestions System in Python, Java, C++, TypeScript and C

Search Suggestions System in Python
class Solution:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        products.sort()
        result = []
        prefix = ""
        for ch in searchWord:
            prefix += ch
            lo, hi = 0, len(products)
            while lo < hi:
                mid = (lo + hi) // 2
                if products[mid] >= prefix:
                    hi = mid
                else:
                    lo = mid + 1
            result.append([p for p in products[lo:lo + 3] if p.startswith(prefix)])
        return result
Search Suggestions System in Java
class Solution {
    public List<List<String>> suggestedProducts(String[] products, String searchWord) {
        Arrays.sort(products);
        List<List<String>> result = new ArrayList<>();
        String prefix = "";
        for (char ch : searchWord.toCharArray()) {
            prefix += ch;
            int lo = 0, hi = products.length;
            while (lo < hi) {
                int mid = (lo + hi) >>> 1;
                if (products[mid].compareTo(prefix) >= 0) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            }
            List<String> picks = new ArrayList<>();
            for (int k = lo; k < Math.min(lo + 3, products.length) && products[k].startsWith(prefix); k++) {
                picks.add(products[k]);
            }
            result.add(picks);
        }
        return result;
    }
}
Search Suggestions System in C++
class Solution {
public:
    vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
        sort(products.begin(), products.end());
        vector<vector<string>> result;
        string prefix;
        for (char ch : searchWord) {
            prefix += ch;
            int lo = 0, hi = products.size();
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (products[mid] >= prefix) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            }
            vector<string> picks;
            for (int k = lo; k < min(lo + 3, (int)products.size()) && products[k].compare(0, prefix.size(), prefix) == 0; k++) {
                picks.push_back(products[k]);
            }
            result.push_back(picks);
        }
        return result;
    }
};
Search Suggestions System in TypeScript
function suggestedProducts(products: string[], searchWord: string): string[][] {
    products.sort();
    const result: string[][] = [];
    let prefix = '';
    for (const ch of searchWord) {
        prefix += ch;
        let lo = 0, hi = products.length;
        while (lo < hi) {
            const mid = (lo + hi) >> 1;
            if (products[mid] >= prefix) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        result.push(products.slice(lo, lo + 3).filter((p) => p.startsWith(prefix)));
    }
    return result;
}
Search Suggestions System in C
static int byString(const void* a, const void* b) {
    return strcmp(*(char* const*)a, *(char* const*)b);
}

char*** suggestedProducts(char** products, int productsSize, char* searchWord, int* returnSize, int** returnColumnSizes) {
    qsort(products, productsSize, sizeof(char*), byString);
    int len = strlen(searchWord);
    char*** result = malloc(len * sizeof(char**));
    *returnColumnSizes = malloc(len * sizeof(int));
    *returnSize = len;
    for (int t = 1; t <= len; t++) {
        int lo = 0, hi = productsSize;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (strncmp(products[mid], searchWord, t) >= 0) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        result[t - 1] = malloc(3 * sizeof(char*));
        int count = 0;
        for (int k = lo; k < productsSize && count < 3 && strncmp(products[k], searchWord, t) == 0; k++) {
            result[t - 1][count++] = products[k];
        }
        (*returnColumnSizes)[t - 1] = count;
    }
    return result;
}

Edge Cases & Common Mistakes

  • Taking three products without checking the prefix: the products after the block do not match and must not be suggested.
  • A prefix with no matches: the list for it, and for every longer prefix, is empty.
  • A product equal to the prefix: it is >= the prefix and starts with it, so it is suggested first.
  • Sorting with a numeric comparator in JavaScript: strings need the default sort (or localeCompare for plain lowercase letters).

Summary

Sort the products. For each typed prefix, binary search the first product that is >= the prefix and take up to three products from there that start with it. O((n + L) log n) comparisons.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Sort

    Sort the products lexicographically.

  2. Search each prefix

    For each typed prefix, binary search the first product that is >= the prefix.

  3. Take up to three

    From that index, take at most three products that still start with the prefix.

Frequently asked questions

Why does sorting make this easy?

In sorted order, all products that start with a prefix sit in one consecutive block, and that block begins at the first product that is >= the prefix. The three lexicographically smallest matches are then simply the first three products of the block.


Isn’t this a trie problem?

LeetCode files it under Trie, and a trie works: insert every product, keep up to three sorted words at each node, and walk one node per typed letter. Sorting plus binary search gives the same answer with less code and less memory, which is why it is the approach shown here.


Can the search range shrink between letters?

Yes. A longer prefix’s block lies inside the shorter prefix’s block, so lo never moves left; you can start the next search from the previous lo. Some solutions skip binary search entirely and shrink two pointers inward as each letter is typed. All of these give the same lists.


What does L stand for in the complexity?

L is the length of searchWord. Sorting n products costs O(n log n) comparisons and each of the L prefixes costs one O(log n) search, plus building prefixes and comparing strings, which adds a factor of the string length.

New to the technique behind this problem? Watch it run step by step:

Binary Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description