Flatten a Nested Array
Updated
Problem statement
You are given a valid JSON array string nested. Each element is either a signed integer or another array.
Recursively flatten every nesting level and return all integer leaves in their original left-to-right order. Empty arrays contribute no values.
The interview also discussed exposing this behavior through the JavaScript Array prototype. This executable version uses a JSON string so the same nested input can run in Java, Python, and C++.
Function
flattenNestedArray(nested: String) → int[]Examples
Example 1
nested = "[1,[2,[3,4],5],6]"return = [1,2,3,4,5,6]A left-to-right recursive traversal visits the integer leaves in the displayed order.
Example 2
nested = "[[],[-1],[[2,3]],4]"return = [-1,2,3,4]The empty array contributes nothing, and the remaining integer leaves keep their relative order.
Constraints
nestedis a valid JSON array containing only signed integers and arrays.- Every integer fits in a signed 32-bit value.
- The nesting depth is at most
1000. - The input contains at most
200000integer leaves.
More Freshworks interview questions
Similar questions at other companies
- Evaluate a Nested Math ExpressionGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Ternary Expression to Binary TreeNutanix · ONSITE INTERVIEWNutanix interview questions
- Exclusive Time of FunctionsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Construct a Tree from Level-Order and Inorder TraversalsSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Evaluate an Arithmetic Expression with DivisionMotive · ONSITE INTERVIEWMotive interview questions
- Remove Parentheses from a Plus-Minus ExpressionOracle · PHONE SCREENOracle interview questions
- Decode StringCompass International Holdings · PHONE SCREENCompass International Holdings interview questions
- Flatten a Nested Object Into Dot KeysAdobe · PHONE SCREENAdobe interview questions