LeetCode 1268 Search Suggestions System - Implementation

The approach

Sort products, binary search for each prefix.

function suggestedProducts(products, searchWord): products.sort() result = [] prefix = "" for char in searchWord: prefix += char idx = bisect_left(products, prefix) suggestions = [] for i in range(idx, min(idx + 3, len(products))): if products[i].startswith(prefix): suggestions.append(products[i]) result.append(suggestions) return result

O(nlogn+mlogn)O(n \log n + m \log n) time.