Design an autocomplete suggestions API
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
## Problem: Autocomplete suggestions (Trie)
You are building an autocomplete feature.
### Input
- A dictionary of `n` unique words `words[i]` (lowercase a–z).
- An integer array `freq[i]` where `freq[i]` is the usage count of `words[i]`.
- Then `q` queries. Each query provides:
- a `prefix` string
- an integer `k` (number of suggestions requested)
### Output
For each query, return up to `k` suggested completions:
- A completion is any word that starts with `prefix`.
- Rank by **higher frequency first**.
- Break ties by **lexicographical order**.
### Follow-up
Support updates:
- Operation `add(word, delta)` increases that word’s frequency by `delta` (word may be new).
- Queries after updates must reflect the new frequencies.
### Constraints (reasonable interview assumptions)
- `1 ≤ n, q ≤ 2e5`
- `1 ≤ |word|, |prefix| ≤ 50`
- Total characters across all words/queries can be large; solutions should be better than scanning all words per query.
Explain what data structure you would use (e.g., Trie) and implement the required operations.
Quick Answer: This question evaluates understanding of string-oriented data structures (e.g., prefix trees/tries), ranked retrieval and dynamic updates, testing skills in efficient prefix search, frequency-based ordering, and lexicographical tie-breaking.
Process add/query operations and return completions ranked by higher frequency then lexicographic order.
Examples
Input: (['apple', 'app', 'ape', 'bat'], [5, 7, 5, 3], [('query', 'ap', 2)])
Expected Output: [['app', 'ape']]
Explanation: Rank by frequency.
Input: (['a', 'ab'], [1, 1], [('add', 'aa', 5), ('query', 'a', 3)])
Expected Output: [['aa', 'a', 'ab']]
Explanation: New word after update.
Input: (['cat'], [2], [('query', 'z', 5)])
Expected Output: [[]]
Explanation: No matches.
Hints
- For production, store ranked suggestions in a trie; this deterministic version scans the maintained dictionary.