Problem · Array

Flatten Nested Array

Learn this problem
MediumRoblox logoRobloxFULLTIMEPHONE SCREEN
See Roblox hiring insights

Problem statement

You are given a JSON-style string nested representing an arbitrarily nested array of integers. Return every integer in left-to-right order as a single array.

An array element may be an integer or another array. Empty arrays contribute no values. The input may contain whitespace and negative integers.

In the interview, be prepared to explain both a recursive traversal and a non-recursive traversal. For this executable version, either correct approach is accepted.

Function

flatten(nested: String) → int[]

Examples

Example 1

nested = "[1,[2,[3,4],5],6]"return = [1, 2, 3, 4, 5, 6]

Depth-first left-to-right traversal visits the integers in the displayed order.

Example 2

nested = "[[],[1],[[2,3]],4]"return = [1, 2, 3, 4]

Empty arrays add nothing, while deeper arrays are traversed normally.

Example 3

nested = "[]"return = []

The empty nested array contains no integers.

Example 4

nested = "[-10, [0, -2], 7]"return = [-10, 0, -2, 7]

Whitespace and negative integers are accepted by the execution adapter.

Constraints

  • 2 <= nested.length <= 100000
  • nested is a valid JSON-style nested array containing integers and arrays only.
  • Integers fit in a 32-bit signed value.
  • The total number of integers is at most 10000.

More Roblox problems

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