# Hidden Depths

> Each dot marks a level. Rebuild the tree it stands for.

Canonical URL: <https://datadriven.io/problems/hidden_depths>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

A config loader returns settings as a flat dict whose keys encode their depth with dots, like `a.b.c` for a value three levels down. Return the equivalent nested dict, where each dot-separated segment of a key becomes one level deeper and the value lands at the end of its path; a key with no dots stays at the top level.

## Example 1

Input:

```
flat = {"d":3,"a.b":1,"a.c":2}
```

Output:

```
{"d":3,"a":{"b":1,"c":2}}
```

## Example 2

Input:

```
flat = {"x.y.z":10}
```

Output:

```
{"x":{"y":{"z":10}}}
```

## Worked solution and explanation

### What this really is

Strip off the config-loader costume and this is path insertion into a tree of plain dicts, where a later key often lands inside a branch an earlier key already built. Everyone splits on dots. What separates candidates is the walk: for each segment except the last you descend one level, creating a dict only if that level is missing, and the final segment receives the value. Create the level unconditionally and the second key under `server.ports` wipes the first, so `http` vanishes and only `https` survives. Treat the last segment like the rest and the value gets buried under an empty dict.

---

### Break it down

#### Step 1: Split each key into path segments

'database.host.port' becomes ['database', 'host', 'port']. A key with no dot becomes a single-element list, which is why dotless keys land at the top level with no special case.

#### Step 2: Walk to the parent, creating levels only when missing

Hold a cursor at the result dict. For each segment except the last, check for a child dict there: create one only if it is missing, then move the cursor into it. That check is what lets a later key like 'a.c' reuse the 'a' dict that 'a.b' already built instead of replacing it.

#### Step 3: Drop the value at the last segment

Once the cursor sits at the deepest parent, assign the value under the final segment. This is the one line that must live outside the descent loop.

---

### The solution

**Iterative path walking**

```python
def unflatten(flat: dict) -> dict:
    result = {}
    for key, value in flat.items():
        parts = key.split(".")
        current = result
        for segment in parts[:-1]:
            if segment not in current:
                current[segment] = {}
            current = current[segment]
        current[parts[-1]] = value
    return result
```

> **Linear in the total number of segments**
>
> Time and space are both **O(n * d)**, where n is the number of keys and d is the average segment count: each key is split once and walked once, and the built tree holds at most one node per segment. There is no recursion, so deeply dotted keys never touch the call stack.

> **Handle the last segment outside the loop**
>
> The tell of seniority is iterating `parts[:-1]` and handling the last segment separately. Candidates who loop over every segment and try to special-case the assignment inside the loop usually produce an off-by-one that nests the value under a stray empty dict.

> **A key that is also a parent breaks the walk**
>
> If `'a.b' = 1` arrives before `'a.b.c' = 2`, the cursor finds an int where it expected a dict: `'b' not in current` is False, `current = current['b']` hands you an int, and the next assignment throws. Ask up front whether the input is conflict-free, or decide explicitly between overwrite and raise. Silently swallowing it is the real mistake.

---

## Common follow-up questions

- How would you handle array indices in the path, like 'a.0.b'? _(Tests creating lists at numeric segments instead of dicts.)_
- How would you flatten a nested dict back into dot-keyed form? _(Tests recursive traversal with path accumulation, the inverse transform.)_
- What if a key segment could itself contain an escaped dot? _(Tests splitting on unescaped dots only, which needs real parsing rather than a plain split.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/hidden_depths)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.