Leetcode 1268: Search Suggestions System

grid47
grid47
Exploring patterns and algorithms
Jul 3, 2024 6 min read

You are given a list of unique product names and a search word. As each character of the search word is typed, you need to suggest up to three products that have a prefix matching the current search word. If there are more than three products with the same prefix, return the three lexicographically smallest products.
Problem
Approach
Steps
Complexity
Input: A list of unique product names and a search word string.
Example: products = ["tablet","telescope","test","terrace","time"] searchWord = "test"
Constraints:
• 1 <= products.length <= 1000
• 1 <= products[i].length <= 3000
• 1 <= sum(products[i].length) <= 2 * 10^4
• All the strings in products are unique.
• 1 <= searchWord.length <= 1000
Output: Return a list of lists where each list contains at most three products that start with the prefix corresponding to the characters typed so far in searchWord.
Example: [["tablet", "telescope", "test"], ["tablet", "telescope", "test"], ["test", "telescope"], ["test", "telescope"], ["test"]]
Constraints:
• Each list in the output should contain at most three products.
Goal: Find the products that match the current prefix and return the three lexicographically smallest products at each step.
Steps:
• 1. Sort the product names lexicographically.
• 2. For each character in the search word, create the current prefix.
• 3. Find products that match the current prefix and return at most three of them.
Goal: The input grid has size m x n, where m and n are both at least 1 and at most 1000. The product strings and searchWord are strings consisting of lowercase English letters.
Steps:
• 1 <= products.length <= 1000
• 1 <= products[i].length <= 3000
• 1 <= sum(products[i].length) <= 2 * 10^4
• All the strings in products are unique.
• 1 <= searchWord.length <= 1000
Assumptions:
• The products list contains unique strings.
• The search word is a non-empty string.
Input: products = ["tablet","telescope","test","terrace","time"] searchWord = "test"
Explanation: As each character of 'test' is typed, the system suggests products that start with the corresponding prefix. At each step, it returns up to three products, sorted lexicographically.

Input: products = ["banana","berry","cherry","date"] searchWord = "berry"
Explanation: In this case, the search word is 'berry'. Since 'berry' is the only product starting with 'b', after each character is typed, only 'berry' will be suggested.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus