Amazon | Phone | Front End Engineer
Anonymous User
5180

Given a series of child-parent relations like
['dog', 'mammal'],
["shark, fish"],
["cat", "mammal"],
["mammal", "animal"],
['fish', 'animal']

capture the relationship of these entities so you can print the
relationships in a nested format at any point.

Notes:

  • Siblings may be returned in any order.
  • Your add function will be called multiple times to add relationships

Example Outputs (any are valid):

Option 1:
animal
  fish
    shark
  mammal
    dog
    cat

Option 2:
{
  "value": "animal",
  "children": [
    {
      "value": "fish",
      "children": [
        {
          "value": "shark",
          "children": []
        }
      ]
    },
    {
      "value": "mammal",
      "children": [
        {
          "value": "dog",
          "children": []
        },
        {
          "value": "cat",
          "children": []
        }
      ]
    }
  ]
}

Option 3:
{
  "animal": {
    "fish": {
      "shark": {}
    },
    "mammal": {
      "cat": {},
      "dog": {}
    }
  }
}
Comments (13)