LeetCode 1268 Search Suggestions System - Why Naive Fails

The trap

For each prefix, filter products that start with it, sort, and take the first 3.

With nn products and search word of length mm, you filter nn products mm times: O(mn)O(m \cdot n).

Can you avoid rescanning all products for each prefix?