Decode an Encrypted Paragraph Tree
Jane StreetSoftware Engineer · Technical ScreenLast updated
This question evaluates skills in string parsing, tree serialization/deserialization, and bijective substitution cipher handling, assessing competency in parsing nested structures, character mapping, and traversal within the Coding & Algorithms domain.
Decode an Encrypted Paragraph Tree
A document is stored as a tree of paragraphs. Each node holds a paragraph text — a string of lowercase English letters and spaces, possibly empty — and an ordered list of child nodes.
The document was encoded in two steps:
- Substitution cipher. Given a
keythat is a permutation of the 26 lowercase letters, every letter of every paragraph was substituted: the letter'a' + iwas replaced bykey[i]. Spaces were left unchanged. - Pre-order serialization. The tree was flattened into a single string: each node became
"(" + encodedText + serializedChild1 + serializedChild2 + ... + ")"
with children serialized in order. Because paragraph texts never contain parentheses, ( and ) unambiguously mark node boundaries.
Given key and the serialized string s, which encodes exactly one root node, decode the document and return the tree as nested lists: each node is represented as [text, [child1, child2, ...]], where text is the fully decoded paragraph and the second element is the (possibly empty) list of its children in order.
Examples
Example 1
Input: key = "bcdefghijklmnopqrstuvwxyza"
s = "(ij(bc)(de))"
Output: ["hi", [["ab", []], ["cd", []]]]
Here key maps each letter to the next one ('a' -> 'b', ..., 'z' -> 'a'), so decoding maps each letter back: "ij" -> "hi", "bc" -> "ab", "de" -> "cd". The root "hi" has two leaf children.
Example 2
Input: key = "qwertyuiopasdfghjklzxcvbnm"
s = "(ug gf(xh(rgvf))())"
Output: ["go on", [["up", [["down", []]]], ["", []]]]
Under this key, 'g' -> 'u', 'o' -> 'g', 'u' -> 'x', 'p' -> 'h', 'd' -> 'r', 'w' -> 'v', 'n' -> 'f'; spaces are unchanged. The root decodes to "go on" and has two children: "up" (which has one child "down") and a node with empty text.
Constraints
keyhas length 26 and is a permutation of the lowercase English alphabet.1 <= s.length <= 10^5, andsis a valid serialization of exactly one root node.- The tree has at most
10^4nodes. - Every paragraph text consists only of lowercase English letters and spaces, and may be empty.
- An
O(s.length)solution is expected.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.