Skip to the page

Utility functions · mid

Flat list to tree (and back)

Turning a flat list of { id, parentId } rows into a nested tree takes O(n) with one pass that builds an id -> node map and another that attaches each node to its parent's children, treating parentId: null as a root.

The notes

What you must know

  • Two passes: (1) create every node with children: [] in a Map by id; (2) for each node, push it into its parent's children, or into roots if parentId is null.
  • One pass also works if you create placeholder parents when a child appears before its parent.
  • Orphans (parent missing): decide whether to treat them as roots or drop them; detect cycles with a visited set.
  • Sort children after building if the UI needs an order.
  • Tree -> flat: a DFS that records parentId. Tree -> path list for breadcrumbs.
  • The result feeds recursive UI: file explorer sidebars and nested comments.
  • Nested loops (search the whole list for each parent) are O(n²), the trap the Frontend Interview Handbook warns about.

The red pen

Common traps: mistake → fix

  • Mistake: O(n²) parent search.

  • Mistake: Mutating the input rows (copy them into nodes).

  • Mistake: Assuming parents always come before children.

Easy to hard

Questions interviewers ask, easy to hard

  1. Convert a flat list to a tree. (Flipkart PSDS round, Feb 2026)
  2. Do it in O(n).
  3. Handle orphans and cycles.
  4. Parse a CSV into a tree. (Dream11, 2025)
  5. Render it as a recursive file explorer.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview