Unscramble a Cipher-Encoded Nested Outline
Stacks & QueuesAuto-graded · 18 test casesLast updated
Parse a parenthesized pre-order tree string with a stack and undo a letter-substitution cipher, where each node's text is the run just before its closing parenthesis.
Unscramble a Cipher-Encoded Nested Outline
An outline is stored as a tree. Each node carries a short string of lowercase letters and spaces (it may be empty) and an ordered list of children.
The outline was written out in two stages:
-
Letter substitution. A string
cipher_key, which is a permutation ofa-z, was used to scramble every letter. The letter at alphabet positioni('a'is 0) was replaced bycipher_key[i]. Spaces were not changed. -
Pre-order flattening. Each node was written as an opening parenthesis, then its scrambled text, then the flattened form of each child in order, then a closing parenthesis:
"(" + scrambledText + child1 + child2 + ... + ")"Node texts never contain parentheses, so the parentheses mark node boundaries.
You are given cipher_key and encoded, the flattened string of exactly one root node. Rebuild the tree and return it as nested lists. Every node is a two-element list [text, children], where children is the list of the node's child nodes in their original order (empty for a leaf).
What goes into text
Scan encoded from left to right. The text of a node is the decoded run of non-parenthesis characters that sits directly before that node's own closing ):
- For a leaf node, this is the whole decoded text written after its
(. Spaces are kept exactly as they appear, including leading and trailing ones. An empty text stays"". - For a node that has at least one child, the characters written before its first child are not reported. Its
textis"", because the run right before its closing)is empty (that)directly follows the last child's)).
In short, only leaves report their decoded text in the result, and every node with children has text equal to "".
Constraints
cipher_keyhas length 26 and is a permutation of the lowercase English letters.1 <= len(encoded) <= 10^5, andencodedis a valid flattening of exactly one root node.- The tree has at most
10^4nodes. - Node texts contain only lowercase letters and spaces, and may be empty.
- A solution that runs in time linear in
len(encoded)is expected. - The tree may be a chain 10^4 nodes deep, so be careful with recursion.
Examples
Example 1
Input: decode_cipher_tree('bcdefghijklmnopqrstuvwxyza', '(ij(bc)(de))')
Output: ['', [['ab', []], ['cd', []]]]
Example 2
Input: decode_cipher_tree('qwertyuiopasdfghjklzxcvbnm', '(ug gf(xh(rgvf))())')
Output: ['', [['', [['down', []]]], ['', []]]]
Hints
Hint 1
Decoding is the inverse of the substitution: the character cipher_key[i] must map back to the letter at position i. Build this table once.
Hint 2
Scan the string once and keep a stack of nodes that have been opened but not yet closed. A new node is a child of whichever node is on top of the stack.
Hint 3
Keep a buffer of decoded characters. Clear it whenever you see a parenthesis. When you reach ')', assign the buffer as the text of the node on top of the stack, then pop that node.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two separate things must be undone: the letter substitution and the flattening.
Substitution. Encoding sent the letter at position i to cipher_key[i], so decoding sends cipher_key[i] back to the letter at position i. Build this inverse mapping once. Spaces are not in the table, so they pass through unchanged.
Flattening. The string is a pre-order bracket sequence, so a stack of currently open nodes parses it in one pass, together with a buffer of decoded characters:
- On
(, create a node["", []]. Append it to the children of the node on top of the stack (if any), push it, and clear the buffer. - On
), set the text of the node on top of the stack to the buffer contents, clear the buffer, and pop the node. The last node popped, when the stack becomes empty, is the root. - On any other character, append its decoded form to the buffer.
Because the buffer is cleared at every parenthesis, a node that has children is closed with an empty buffer (its last child's ) just cleared it), so its text is "". A leaf is closed with its own decoded text in the buffer.
An explicit stack is used instead of recursion because a chain of 10^4 nodes would exceed Python's default recursion limit.
Why it is correct
cipher_keyis a permutation, so the substitution is a bijection and the inverse table restores each letter exactly. Spaces were never changed.- The stack always holds the opened-but-unclosed nodes from outermost to innermost, so a newly opened node's parent is the top of the stack. Appending children as they open preserves their order.
- The buffer holds exactly the decoded characters seen since the most recent parenthesis, which matches the text rule: leaves get their text, nodes with children get
"". - The input is valid, so the stack empties exactly once, at the final
), and that node is the root.
Complexity
- Time: O(n) with n =
len(encoded). Each character is handled once. - Space: O(n) for the output tree, the stack and the buffer.
Reference solution
from typing import List
def decode_cipher_tree(cipher_key: str, encoded: str) -> List:
# Inverse substitution: scrambled letter cipher_key[i] -> letter 'a' + i.
inverse = {}
for plain_index, scrambled in enumerate(cipher_key):
inverse[scrambled] = chr(plain_index + ord('a'))
stack = []
root = None
buffer = []
for ch in encoded:
if ch == '(':
node = ['', []]
if stack:
stack[-1][1].append(node)
stack.append(node)
buffer = []
elif ch == ')':
stack[-1][0] = ''.join(buffer)
buffer = []
root = stack.pop()
else:
buffer.append(inverse.get(ch, ch))
return root