Merge and Serialize N-ary Trees
Company: LinkedIn
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: hard
Interview Round: Technical Screen
# Merge and Serialize N-ary Trees
You are asked to merge two N-ary trees and then serialize the result, but no merge key, value-conflict rule, child-order rule, or wire format has been specified. Explain the questions you must resolve. Then choose one coherent contract, outline an implementation, and design a deterministic serialization and parser for that contract.
### Constraints & Assumptions
- Input trees are finite and acyclic.
- Node values alone may not be unique.
- Children may be ordered or unordered depending on the chosen contract.
- The serialized representation must distinguish structure unambiguously.
- Inputs must not be mutated unless explicitly agreed.
### Clarifying Questions to Ask
- Do nodes merge by stable ID, path position, or value?
- What happens when matching nodes have different payloads?
- Are duplicate children valid, and is child order meaningful?
- Must serialization support arbitrary text, schema evolution, and malformed-input detection?
### Part 1 - Define merge semantics
State node identity, value-conflict, child-order, duplicate, and ownership rules.
#### What This Part Should Cover
- Why several reasonable contracts yield different trees
- Stable keys or a positional alternative
- Deterministic conflict resolution
- Deep-copy versus structural sharing
### Part 2 - Merge under the chosen contract
Give an algorithm, correctness argument, complexity, and behavior for malformed inputs.
#### What This Part Should Cover
- Matching and unmatched children
- Duplicate-key validation
- Iterative handling of deep trees
- Input immutability
### Part 3 - Serialize and parse
Specify a versioned, length-safe format with a canonical child order and validation rules.
#### What This Part Should Cover
- Unambiguous boundaries
- Round-trip and canonicalization guarantees
- Resource limits and invalid data
- Schema evolution
```hint Contract precedes code
Two implementations cannot be compared until node identity, conflict handling, and child order define one expected merged tree.
```
### What a Strong Answer Covers
- Recognition that the source prompt lacks a canonical executable result
- One explicit, internally consistent merge contract
- A correct algorithm with ownership and complexity analysis
- Deterministic, validated round-trip serialization
### Follow-up Questions
1. How would the algorithm change if child order were semantically meaningful?
2. Can structural sharing be safe when callers may mutate nodes?
3. How would you stream a tree too large to hold in memory?
Quick Answer: Define explicit N-ary tree merge semantics, implement the contract without mutating inputs, and design a deterministic, validated round-trip format.