cswork / libraryOpen practice workspace

Coding questions · TikTok

Flatten object & Promise.all

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.

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.

Flatten Nested Dictionary Paths

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

Examples

Example 1

Input: obj = {"a": {"b": 1, "c": {"d": 2}}, "e": 3}
Output: {"a.b": 1, "a.c.d": 2, "e": 3}

Explanation: Concatenate dictionary keys with dots. Only non-dict, non-list values are included.

Example 2

Input: obj = {"a": [1, {"b": 2}, [], {"c": [3, 4]}], "x": {}}
Output: {"a.0": 1, "a.1.b": 2, "a.3.c.0": 3, "a.3.c.1": 4}

Explanation: List indices are used as path segments. Empty dicts/lists produce no entries.

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.

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