Katkat

Flatten Nested Comments

NextdooriOS Engineer · Technical Screen

Last updated

This problem tests your ability to traverse a nested tree structure (comments) and flatten it into a linear representation while respecting hierarchical depth levels.

Flatten Nested Comments

In a social networking app, comments can be nested under parent comments, forming a tree-like structure. You are given a root list of Comment objects. Each comment may contain a list of replies, which are also Comment objects.

Your task is to implement a function that flattens this nested structure into a single list of objects, while preserving the visual hierarchy by adding a depth property to each comment.

Data Structure

class Comment {
    let id: String
    let text: String
    let replies: [Comment]
    var depth: Int = 0 // To be populated during flattening

    init(id: String, text: String, replies: [Comment] = []) {
        self.id = id
        self.text = text
        self.replies = replies
    }
}

Function Signature

func flattenComments(rootComments: [Comment]) -> [Comment]

Examples

Input: A structure like: C1 -> [C2 -> [C3], C4]

Output: [C1(depth: 0), C2(depth: 1), C3(depth: 2), C4(depth: 1)]

Constraints

  • The nesting depth is unknown but will not cause a stack overflow in a typical UI scenario.
  • You should return a new list of comment objects with their depth property correctly assigned.
  • The order of comments must be consistent with a pre-order traversal (Parent before Children, Children in order of appearance).

Hints

Hint 1

Consider using recursion to traverse the `replies` array while passing the current depth as a parameter.

Hint 2

If you prefer an iterative approach, consider using a stack to manage the comments and their associated depths while traversing.

Hint 3

Think about whether you should modify the original objects in place or create shallow copies to keep the function pure.

Follow-up questions

  • How would your implementation change if you needed to limit the total depth to only 3 levels?
  • What are the time and space complexity implications of your solution regarding the number of total comments N?
  • If the input data was extremely large (e.g., 100,000+ comments), how would you optimize the memory usage?