Quick Overview

This question evaluates proficiency in JavaScript data manipulation and asynchronous programming, testing competencies in transforming nested objects into single-level key paths and reproducing Promise.all semantics.

Flatten object & Promise.all

Company: TikTok

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

##### Question Given a nested JavaScript object, write a function to flatten it so that nested keys are converted to a single-level path (e.g., {a:{b:1}} -> {'a.b':1}). Implement Promise.all from scratch in JavaScript; it should take an iterable of promises/values and return a single promise that resolves when all inputs resolve or rejects when any input rejects.

Overview: This question evaluates proficiency in JavaScript data manipulation and asynchronous programming, testing competencies in transforming nested objects into single-level key paths and reproducing Promise.all semantics.

Given a nested dictionary obj whose values may be dictionaries or lists (both possibly nested), return a new flat dictionary mapping dot-separated paths to leaf values. Build paths by concatenating dictionary keys and list indices with a dot. Only values that are neither dictionaries nor lists are emitted as leaves. Do not create entries for empty dictionaries or empty lists. Assume all dictionary keys are strings that do not contain a dot. Do not mutate the input.

Constraints

  • 1 <= total number of dictionary entries + list items <= 100000
  • Maximum nesting depth <= 500
  • All dictionary keys are strings without '.'
  • Leaf values can be int, float, str, bool, or None
  • Input must not be mutated

Hints

  1. Use DFS to traverse the structure and build the path as you go.
  2. Maintain a list of path segments and join with '.' when you reach a leaf.
  3. Treat dictionaries and lists separately; skip empty ones.

Loading coding console...

Show the approach

Approach

Perform a depth-first traversal. Keep a stack (list) of path segments. For dictionaries, append the key; for lists, append the index. When a leaf (neither dict nor list) is reached, join the segments with '.' to form the path and store the value. Empty dicts/lists are skipped so they do not emit entries.

Time complexity:
O(N), where N is the total number of dictionary entries and list items; path joins occur once per leaf
Space complexity:
O(N) for the output plus O(H) auxiliary stack space, where H is the max depth