⚡Flashcard Drill➔
NeetCode #292LC-1268MediumBinary Search
← Back to All Problems

#292 · #1268 · Search Suggestions System(搜索推荐系统)

📌 Problem Statement & Constraints

You are given an array of strings products and a string searchWord. After typing each character of searchWord, return up to three lexicographically smallest product names that have the current prefix. Return the results as a list of lists. Constraints: 1 <= products.length <= 1000, 1 <= products[i].length, searchWord.length <= 1000.

💡 Core Algorithmic Approaches

  1. Sort products once. Then for each prefix, all matching products form a contiguous block starting at bisect_left(products, prefix).
  2. Scan at most three entries from that index, stopping as soon as a product no longer starts with the prefix.
  3. The early stop is important: without it you might return products that merely sort after the prefix.
  4. Sorting once gives O(n log n + |searchWord| * (log n + 3)) overall.

💻 Benchmark Python3 Implementation

class Solution:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        from bisect import bisect_left
        products.sort()
        res = []
        prefix = ""
        for ch in searchWord:
            prefix += ch
            i = bisect_left(products, prefix)   # first product >= prefix
            cur = []
            for j in range(i, min(i + 3, len(products))):
                if products[j].startswith(prefix):
                    cur.append(products[j])
                else:
                    break                      # no further matches
            res.append(cur)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n + L log n) where L is the length of searchWord: the sort plus a binary search per prefix.
💾 Space Complexity
O(1) beyond the output (the sort is in place).

⚠️ Interview Pitfalls & Follow-ups

  • Scanning the whole product list for each prefix: O(n * L * m).
  • Omitting the startswith check: products that sort after the prefix but do not share it would be wrongly included.
  • Forgetting to break: the same issue, and it wastes iterations.
  • Sorting the products for each prefix: unnecessary; one sort suffices.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

搜索推荐系统

给你一个产品数组 products 和一个字符串 searchWord,products 数组中每个产品都是一个字符串。请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,请按 字典序 返回最小的三个。请你以二维列表的形式,返回输入 searchWord 每个字母后相应的推荐产品的列表。约束:1 ≤ products.length ≤ 1000;1 ≤ products[i].length ≤ 3000;products[i] 中所有字符串互不相同;1 ≤ searchWord.length ≤ 1000;searchWord 由小写英文字母组成。

核心要点

  • 排序 + 二分(标准解) :把 products 字典序排序。对每个前缀,二分找到第一个 ≥ 前缀的位置,然后取最多 3 个以该前缀开头的产品。
  • 为什么排序后前缀相同的产品连续 :字典序排序下,所有以 prefix 开头的字符串必然形成一个连续区间。
  • 校验 startswith :二分只保证「≥ prefix」,可能取到不以 prefix 开头的字符串,因此必须逐个校验。
  • 复杂度 :排序 O(n log n · L),每个前缀 O(log n + 3L)。

常见陷阱

  • 不排序直接扫描所有产品 :每个前缀都要 O(n) 扫描,总计 O(n · m)。排序 + 二分是 O((n + m) log n)。
  • 二分后不校验 startswith :会返回不以该前缀开头的字符串。必须逐个校验。
  • 取 3 个但不校验就停止 :若前 3 个中有不以 prefix 开头的,会导致结果少于 3 个而漏掉后面的合法产品。应先取最多 3 个候选再校验,或校验后再补齐。
  • 每轮重新构造前缀字符串 : prefix += c 的写法是 O(m²),m ≤ 1000 时可接受;更优做法是用 searchWord[:i+1] 。

参考实现

from bisect import bisect_left

class Solution:
    def suggestedProducts(self, products: list[str], searchWord: str) -> list[list[str]]:
        products.sort()                 # 字典序排序
        res = []
        prefix = ''
        for c in searchWord:
            prefix += c
            i = bisect_left(products, prefix)
            # 从 i 开始取最多 3 个以 prefix 开头的产品
            cand = []
            for j in range(i, min(i + 3, len(products))):
                if products[j].startswith(prefix):
                    cand.append(products[j])
            res.append(cand)
        return res