problems / 199

Trie-Based Autocomplete (easy version)

easy trie design strings 1000 ms · 256 MB

Trie-Based Autocomplete (easy version)

Implement an autocomplete system using a trie data structure. Support two operations: inserting words and finding all words with a given prefix.

Input

The first line contains n (1 ≤ n ≤ 1000), the number of operations.

Each of the next n lines contains one operation:

  • INSERT word — add word to the trie. Duplicate inserts have no effect.
  • AUTOCOMPLETE prefix — find all words in the trie that start with prefix, in lexicographic order.

All words and prefixes are non-empty strings of lowercase English letters, each at most 20 characters.

Output

For each AUTOCOMPLETE query, print the matching words in lexicographic order, one per line. If no words match, print nothing (blank line).

After all queries are processed, print the total number of distinct words inserted (on a single line).

Constraints

  • 1 ≤ n ≤ 1000
  • Each word and prefix is 1–20 lowercase English letters
  • Total length of all words and prefixes ≤ 20000
  • Time limit: 1000 ms
  • Memory limit: 256 MB

Example 1

Input

6
INSERT apple
INSERT app
AUTOCOMPLETE app
AUTOCOMPLETE app
INSERT apply
AUTOCOMPLETE app

Output

app
apple
app
apple
app
apple
apply
3

Example 2

Input

5
INSERT hello
AUTOCOMPLETE world
AUTOCOMPLETE hel
INSERT help
AUTOCOMPLETE hel

Output

hello
hello
help
2

Hints · reveal one at a time if you're stuck

Hint 1

A trie shares common prefixes between words. What does the node reached by walking an AUTOCOMPLETE prefix stand for, and which words lie beneath it?

Hint 2

Mark a word's last node when inserting it, and count a word only the first time it is marked. For AUTOCOMPLETE, search from the prefix node visiting children in alphabetical order, and output a word before the longer words that extend it.

report an issue Prefer your own editor? sooks prep 199 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.