Flatten a Nested JSON Object
On this page
Problem statement
Part 1: write
flatten(obj), which turns a nested JSON-style object into a single-level map from path to value. Paths join keys with"."; list elements use their index as the key. Leaf values (strings, numbers, booleans, null) are copied as they are, and an empty object or list is kept as a leaf so nothing is lost.
Part 2: write unflatten(flat), which rebuilds the original nested object. Expect follow-ups on custom separators, keys that contain the separator, and very deep nesting.
This comes up in practical rounds because it mirrors real work: turning nested config or event payloads into column names, environment variables or log fields, and back. There is no single LeetCode original; the closest relatives are tree traversals such as LeetCode 257, Binary Tree Paths.
Example

flatten({
"user": {"name": "Ada", "langs": ["py", "go"], "address": {"city": "Oslo"}},
"active": true
})
-> {
"user.name": "Ada",
"user.langs.0": "py",
"user.langs.1": "go",
"user.address.city": "Oslo",
"active": true
}
flatten({"a": {}, "b": [], "c": null}) -> {"a": {}, "b": [], "c": null}
unflatten(flatten(x)) == x
Constraints (assumed)
- Up to 10⁵ leaves; nesting depth up to 100 (deeper input is a follow-up).
- Keys are strings without the separator; values are JSON values.
What this question tests
- Treating nested data as a tree and walking it with DFS while carrying the path.
- Defining the format precisely: lists, empty containers, separators.
- Writing the inverse and checking the round trip.
Questions to ask first
- How are list elements named? (Here: by index,
langs.0. Some versions uselangs[0].) - What happens to empty objects and lists? (Here: kept as leaf values.)
- Can a key contain the separator? (Here: no, and the code rejects it. See the bug section.)
- Should unflatten turn numeric keys back into lists? (Here: yes, when the keys are exactly 0…n−1.)
- How deep can it get? Recursion depth matters past a few thousand levels.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.