#1268

Search Suggestions System

Medium Trie with top-3 lists

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

As each character of searchWord is typed, return up to three product names (alphabetically smallest) that start with the typed prefix.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: up to 3 suggestions for every prefix typed.

Why this works: insert sorted products; each node keeps the first three words passing through it.

Example: products ["mobile","mouse","moneypot","monitor","mousepad"], type "mouse"

"m" → mobile, moneypot, monitor"mou" → mouse, mousepad

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to keep adding empty lists after the prefix stops matching.

Solve on LeetCode ↗
Complexity
  • Time: O(total characters + m log m) for sorting.
  • Space: O(total characters).
Topic: Trie
🎬 Episode 97: video coming soon