


ARR_2D = [
[0, 1],
[2, 3, 4],
[],
[5]
]
The computed ‘ARR_1D’ should be as follows:
ARR_1D = [0, 1, 2, 3, 4, 5]
So, the printed output will be: 0 1 2 3 4 5
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
The first line of each test case contains an integer ‘N’ denoting the number of rows in ‘ARR_2D’. Then, ‘N’ lines follow.
Each line contains an integer ‘M’ denoting the number of columns in that row and ‘M’ space-separated integers denoting the row values.
For more clarity, please refer to the sample inputs.
For every test case, the values in ‘ARR_1D’ will be printed in a separate line.
1. You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 100
0 <= M <= 100
-10^6 <= Value in each element of ‘ARR_2D’ <= 10^6
Time limit: 1 sec
A simple and less efficient approach will be to convert the given ‘ARR_2D’ into a 1-D array during initialization. We need to store a single pointer that initially points to the start of the 1-D array. Each call of ‘NEXT’ will increment this pointer, and ‘HAS_NEXT’ will return false when the pointer points outside the array.
The ‘FLATTEN_2D’ class stores two variables:
The constructor ‘FLATTEN_2D(ARR_2D)’ is as follows:
The ‘NEXT’ function:
The ‘HAS_NEXT’ function:
Instead of using extra space to store a 1-D array, we can use two variables to point to a position in ‘ARR_2D’. Variable 'ROW' will point to the row, and 'COL' will point to the column in that row. Initialize 'ROW' and 'COL' to point to the first element in ‘ARR_2D’. After each ‘NEXT’ and ‘HAS_NEXT’ call, we update the pointer values. In ‘NEXT’, move to the NEXT column in the current row, and if all columns are traversed, then move to the first column of the NEXT row. In ‘HAS_NEXT’, check for empty rows and move to the NEXT non-empty row.
The 'FLATTEN_2D' class stores three variables:
The constructor ‘FLATTEN_2D(ARR_2D)’ is as follows:
The ‘NEXT’ function:
The ‘HAS_NEXT’ function:
Use an inbuilt iterator 'IT' of type 1-D array’. Initialize 'IT' to point to the first row in ‘ARR_2D’. After each 'NEXT' and ‘HAS_NEXT’ call, we update this iterator. In 'NEXT', we increment 'IT' to point to the current row’s next element. If a row is traversed or is empty, then 'IT' points to ‘end()’ (in C++) or ‘it.HAS_NEXT()’ returns false (in Java). In ‘HAS_NEXT’, check if the current row is traversed or is empty and point 'IT' to the next non-empty row.
The ‘Flatten2D’ class stores three variables:
The constructor ‘Flatten2D(ARR_2D)’ is as follows:
The 'NEXT' function:
The ‘HAS_NEXT’ function: