FastPrepSerialize a Nested Dictionary as JSON

Serialize a Nested Dictionary as JSON

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Serialize a nested value containing strings, lists, and string-keyed dictionaries into a compact JSON string.

The value is encoded by nodes, and row 0 is the root dictionary:

  • ["STRING", value] is a string node.
  • ["LIST", child1, child2, ...] is a list whose remaining fields are child-node indexes in order.
  • ["DICT", key1, child1, key2, child2, ...] is a dictionary whose remaining fields are key and child-index pairs in insertion order.

Child indexes always point to later rows, and every row is reached exactly once. Escape quotation marks, backslashes, newline, carriage return, and tab inside keys and string values. Return JSON without extra whitespace while preserving list and dictionary order.

Function

serializeNestedDictionary(nodes: String[][]) → String

Examples

Example 1

nodes = [["DICT","a","1","c","2"],["STRING","b"],["STRING","d"]]return = "{\"a\":\"b\",\"c\":\"d\"}"

The root dictionary contains two string-valued entries in their encoded order.

Example 2

nodes = [["DICT","items","1"],["LIST","2","3"],["STRING","x"],["DICT","k","4"],["STRING","line\nnext"]]return = "{\"items\":[\"x\",{\"k\":\"line\\nnext\"}]}"

The newline inside the nested string is escaped as \n.

Constraints

  • 1 <= nodes.length <= 100000.
  • Row 0 is a valid DICT row.
  • Every child index is a decimal integer naming a later row.
  • Every dictionary key is unique within its dictionary.
  • Each row is reachable exactly once, so the encoded value is a tree.
  • The total output length is at most 200000.

More Google problems

See Google hiring insights
public String serializeNestedDictionary(String[][] nodes) {
    // Write your code here.
}
nodes[["DICT","a","1","c","2"],["STRING","b"],["STRING","d"]]
expected"{\"a\":\"b\",\"c\":\"d\"}"
Checking account…