FastPrepSerialize and Deserialize an N-Ary Tree

Serialize and Deserialize an N-Ary Tree

Uber logoUber● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Implement a codec for finite rooted ordered N-ary trees with integer values. Process each operation independently and return one result per operation.

  • For serialize, the payload is a canonical tree description: a node is value[child1,child2,...], a leaf is value[], and an empty tree is #. Return a preorder encoding in which every non-null node contributes its value followed by its child count, with tokens separated by one space. The empty tree encodes as #.
  • For deserialize, the payload is a preorder child-count encoding produced by that rule. Rebuild the tree and return its canonical tree description.

Child order must be preserved exactly.

Function

processNaryCodec(operations: String[], payloads: String[]) → String[]

Examples

Example 1

operations = ["serialize","deserialize"]payloads = ["1[2[],3[4[]]]","1 2 2 0 3 1 4 0"]return = ["1 2 2 0 3 1 4 0","1[2[],3[4[]]]"]

The first operation encodes the ordered tree in preorder. The second reconstructs the same tree and emits its canonical description.

Example 2

operations = ["serialize","deserialize"]payloads = ["#","-5 0"]return = ["#","-5[]"]

The null tree has the single-token encoding #, while a leaf stores its value and a zero child count.

Constraints

  • 1 <= operations.length == payloads.length <= 100
  • Every operation is serialize or deserialize, and each payload is valid for its operation.
  • Across all operations there are at most 10000 nodes and at most 100000 payload characters.
  • Node values are signed 32-bit integers.

More Uber problems

See Uber hiring insights
public String[] processNaryCodec(String[] operations, String[] payloads) {
    // Write your code here.
}
operations["serialize","deserialize"]
payloads["1[2[],3[4[]]]","1 2 2 0 3 1 4 0"]
expected["1 2 2 0 3 1 4 0", "1[2[],3[4[]]]"]
Checking account…