call(back)
Algorithms & Data StructuresmediumSign in to star problems

Serialize a Dictionary Trie

Build a trie from a list of words and serialise it: write each node's children in alphabetical order, each as its letter, then * if a word ends there, then its own children wrapped in parentheses when it has any. The root's children are written without a wrapper. Then write the inverse: deserializeTrie(s) returns an object with contains(word).

serializeTrie(["app", "apple", "bat"])  ->  "a(p(p*(l(e*))))b(a(t*))"
serializeTrie(["to", "tea", "ted"])     ->  "t(e(a*d*)o*)"
serializeTrie(["a", "ab"])              ->  "a*(b*)"

Hints

Hint 1

Serialising is a pre-order walk that sorts each node's children; the grammar is child := letter '*'? ( '(' children ')' )?.

Hint 2

Deserialising is a recursive parser with a cursor: read a letter, an optional star, and if the next character is ( parse the children until the matching ).

Asked at