Problem · String

N-Ary Tree Codec Operations

Learn this problem
HardLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

Implement a codec for ordered, nonempty N-ary trees whose nodes contain nonnegative integer values. Process a finite batch of operations and return one result per operation.

Tree text

A leaf is written as its decimal value. A non-leaf is written as its value followed by its children in parentheses, separated by commas. Child order is significant. For example, 1(2,3(4,5)) has root 1, leaf child 2, and child 3 with children 4 and 5.

Wire format

Serialize a tree by preorder traversal. Write each node as value:childCount and join node tokens with |. The example above becomes 1:2|2:0|3:2|4:0|5:0.

Operations

  • ["SERIALIZE", treeText]: parse the tree text and return its wire format.
  • ["DESERIALIZE", wire]: reconstruct the tree and return its canonical tree text.

Every supplied representation is valid. Return all operation results in their original order.

Function

transformNaryCodec(operations: String[][]) → String[]

Examples

Example 1

operations = [["SERIALIZE","1(2,3(4,5))"],["DESERIALIZE","7:3|8:0|9:1|10:0|11:0"]]return = ["1:2|2:0|3:2|4:0|5:0","7(8,9(10),11)"]

The first operation records each node in preorder together with its number of children. In the second operation, the root has three children; the middle child has one child of its own.

Example 2

operations = [["SERIALIZE","42"],["DESERIALIZE","5:2|6:0|7:0"]]return = ["42:0","5(6,7)"]

A leaf has child count 0. The second wire representation describes a root with two leaf children.

Example 3

operations = [["DESERIALIZE","1:1|2:1|3:1|4:0"],["SERIALIZE","0(10(20),30)"]]return = ["1(2(3(4)))","0:2|10:1|20:0|30:0"]

The first representation is a four-node chain. The second tree preserves the left-to-right order of the subtree rooted at 10 and the leaf 30.

Constraints

  • 1 ≤ operations.length ≤ 500.
  • Each operation is exactly ["SERIALIZE", treeText] or ["DESERIALIZE", wire].
  • Every tree is nonempty, ordered, and contains at most 2000 nodes.
  • Every node value is in [0, 10^9].
  • Every input representation follows its grammar exactly and contains no spaces.
  • The total number of nodes across all operations is at most 20000.

More LinkedIn problems

drafts saved locally
public String[] transformNaryCodec(String[][] operations) {
    // Write your code here.
}
operations[["SERIALIZE","1(2,3(4,5))"],["DESERIALIZE","7:3|8:0|9:1|10:0|11:0"]]
expected["1:2|2:0|3:2|4:0|5:0", "7(8,9(10),11)"]
checking account