#K65912. Flatten Nested List at Specified Depth

    ID: 32303 Type: Default 1000ms 256MiB

Flatten Nested List at Specified Depth

Flatten Nested List at Specified Depth

Given a nested list that may contain integers and other lists (nested arbitrarily), your task is to flatten the elements at a given depth level. Specifically, when the depth parameter is ( d ), you must flatten all lists that are nested exactly at that level into their parent list, while leaving other levels unchanged.

For example, consider the list [[1, 2], [3, 4, [5, 6]], 7, [8, [9, [10]]]].

  • If \( d = 2 \), the result is [[1, 2], [3, 4, 5, 6], 7, [8, 9, [10]]].
  • If \( d = 1 \), the result is [1, 2, 3, 4, [5, 6], 7, 8, [9, [10]]].
Note that if \( d = 0 \) the original list remains unchanged. Your solution should handle empty lists and lists with no nested elements gracefully.

inputFormat

The input is read from standard input and consists of two lines:

  1. The first line is a JSON array representing the nested list. It may include integers and nested arrays.
  2. The second line is an integer ( d ) which specifies the depth at which flattening should occur.

outputFormat

Output to standard output a single JSON array that represents the flattened list after performing the flattening operation at the specified depth.## sample

[[1, 2], [3, 4, [5, 6]], 7, [8, [9, [10]]]]
2
[[1,2],[3,4,5,6],7,[8,9,[10]]]