Trie-Based Autocomplete (Medium Version)
This problem extends the easy version (problem 199) by adding a DELETE operation and returning the top-k most frequent words by prefix instead of all words in lexicographic order. You must track word frequencies and support efficient deletion.
Implement an autocomplete system using a trie data structure with frequency tracking. Support three operations: inserting words, deleting words, and finding the top-k most frequently used words with a given prefix.
Input
The first line contains n (1 ≤ n ≤ 3000), the number of operations.
Each of the next n lines contains one operation:
INSERT word— addwordto the trie, incrementing its frequency by 1. Duplicate inserts increase frequency.DELETE word— decrement the frequency ofwordby 1. If the frequency drops to zero, the word is removed from the trie. Deleting a word that does not exist or has frequency zero is a no-op (silent failure).AUTOCOMPLETE prefix k— find thekmost frequently used words in the trie that start withprefix. If multiple words have the same frequency, return them in lexicographic order. If fewer thankwords match the prefix, return all of them.
All words and prefixes are non-empty strings of lowercase English letters, each at most 20 characters. k is between 1 and 100.
Output
For each AUTOCOMPLETE query, print the matching words (up to k most frequent) in the specified order, one per line. If no words match the prefix, print nothing for that query.
After all queries are processed, print the total number of distinct words remaining in the trie (words with frequency ≥ 1) on a single line.
Constraints
- 1 ≤ n ≤ 3000
- Each word and prefix is 1–20 lowercase English letters
- 1 ≤ k ≤ 100
- Total length of all words and prefixes ≤ 60000
- Time limit: 1000 ms
- Memory limit: 256 MB
Notes
The total number of distinct words remaining counts only words with frequency ≥ 1 after all INSERT and DELETE operations.