Dataford
Interview Guides
Upgrade
All questions/Coding/Flatten Nested JSON Object Arrays

Flatten Nested JSON Object Arrays

Medium
Coding
Asked at 1 company1ArraysRecursionStack
Also asked at
Discord

Problem

Flatten a deeply nested array whose elements are either JSON objects (dict) or more arrays. Return all objects in left-to-right order without using recursion.

Examples

Example 1
Input[{"id": 1}, [{"id": 2}, [{"id": 3}]], {"id": 4}]Output[{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}]WhyNested arrays are expanded while preserving order.
Example 2
Input[[[{"name": "a"}]], [], [{"name": "b"}, [{"name": "c"}]]]Output[{"name": "a"}, {"name": "b"}, {"name": "c"}]WhyEmpty arrays are ignored.

Constraints

  • `0 <= total elements across nesting <= 10^5`
  • Each element is either a `dict` or a `list`
  • Nesting depth can be very large

Problem

Flatten a deeply nested array whose elements are either JSON objects (dict) or more arrays. Return all objects in left-to-right order without using recursion.

Examples

Example 1
Input[{"id": 1}, [{"id": 2}, [{"id": 3}]], {"id": 4}]Output[{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}]WhyNested arrays are expanded while preserving order.
Example 2
Input[[[{"name": "a"}]], [], [{"name": "b"}, [{"name": "c"}]]]Output[{"name": "a"}, {"name": "b"}, {"name": "c"}]WhyEmpty arrays are ignored.

Constraints

  • `0 <= total elements across nesting <= 10^5`
  • Each element is either a `dict` or a `list`
  • Nesting depth can be very large
Practice Python
Python 3.10
Open on desktop for the full Python editor with syntax highlighting and autocomplete.