Problem · Array

Flatten a Nested Array

Learn this problem
MediumFreshworks logoFreshworksFULLTIMEONSITE INTERVIEW

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

  • nested is 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 200000 integer leaves.

More Freshworks problems

drafts saved locally
public int[] flattenNestedArray(String nested) {
  // write your code here
}
nested"[1,[2,[3,4],5],6]"
expected[1,2,3,4,5,6]
checking account