The problem was really fun to solve and uniquely presented compared to other screenings I’ve done.
Question: Given the JSON data of comments, create a react app that renders them in the correct order and with correct nesting.
The comments were in a flat array and each had an id, parentId, etc. The IDE already had the structure of a plain react app and had the JSON stored to a const.
For me, the challenge was determining how to create a structured object efficiently. I can’t remember exactly how I solved it during the tech screen - but it was not the most efficient solution and I still passed. I think the key thing here is that I talked through my solution and asked a lot of questions.
Looking back, the most efficient solution was to loop through the dataset and create two objects:
- parentToChild Map - this is a map which simply contains a map of comment ID to an array of the children. While you loop through the dataset, check if its parentId is in the map. If not, create the index with an array containing the commentId as the value. If it does exist, push the current id into the value.
- post Map (Set could also work for numeric indices) - this is just a collection of post ID to the post data.
Of course you will also have to create a basic react component that displays the comment and then sub-comments (if present). IIRC there was already a basic comment component, but the child comment rendering was not implemented.