FastPrepCanonical N-Ary Tree Codec

Canonical N-Ary Tree Codec

Apple logoApple● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Deserialize the N-ary tree encoded by data, then serialize it into canonical form.

The grammar is node := integer '[' (node (',' node)*)? ']'. Input may contain whitespace and leading zeroes. Canonical output contains no whitespace or leading zeroes.

Function

canonicalizeNaryTree(data: String) → String

Examples

Example 1

data = "1[3[5[],6[]],2[],4[]]"return = "1[3[5[],6[]],2[],4[]]"

The canonical input is preserved after a codec round trip.

Example 2

data = " 01[ -2[] , 003[] ] "return = "1[-2[],3[]]"

Whitespace and leading zeroes are normalized.

Example 3

data = "-7[]"return = "-7[]"

A leaf has an empty child list.

Constraints

  • 1 <= data.length <= 2 * 10^5.
  • The input is a valid tree in the stated grammar.
  • Node values fit signed 32-bit integers.

More Apple problems

See Apple hiring insights
public String canonicalizeNaryTree(String data) {
    // Write your solution here.
}
data"1[3[5[],6[]],2[],4[]]"
expected"1[3[5[],6[]],2[],4[]]"
Checking account…