#C14889. Flatten Nested List with Depth
Flatten Nested List with Depth
Flatten Nested List with Depth
You are given a nested list of integers and an integer \(N\). Your task is to flatten the nested list up to depth \(N\).
More formally, let the nested list be \(L\). Flattening one level of \(L\) means that every element that is a list is replaced by its contents. You must apply this process recursively exactly \(N\) times (or until no more flattening is possible if \(N\) is greater than the actual depth of nesting).
For example, if the input is [1,[2,[3,[4]],5],[6,7]]
and \(N=1\), then the flattened output is [1,2,[3,[4]],5,6,7]
. Note that when \(N=0\) no flattening occurs.
Your solution should read the input from standard input (stdin) and output the result to standard output (stdout) in JSON list format (e.g. [1,2,3]
for a completely flattened list).
inputFormat
The input consists of two lines:
- The first line is a JSON formatted array representing the nested list. For example:
[1,[2,[3,[4]],5],[6,7]]
- The second line is an integer \(N\) representing the depth up to which the list should be flattened.
outputFormat
Output a JSON formatted array which is the flattened list after applying the flatten process up to depth \(N\).
## sample[1,[2,[3,[4]],5],[6,7]]
1
[1,2,[3,[4]],5,6,7]