Last Updated: 26 Nov, 2020

Row Wave Form

Easy
Asked in companies
AmazonVir SoftechCvent

Problem statement

You are given a 2D array with dimensions ‘N*M’. You need to read the array elements row-wise and return a linear array that stores the elements like a wave i.e the 1st-row elements are stored from left to right, 2nd-row elements are stored from right to left, and so on.

Input Format:
The first line of input contains an integer 'T' representing the number of the test cases. Then ‘T' test cases follow.

The first line of each test case contains two space-separated integers, 'N', 'M', the dimensions of the 2D array. 

The next ‘N’ lines consist of ‘M’ space-separated integers denoting the array elements.
Output Format:
For each test case, return a 1D array storing the input array elements like a wave.

Note:

You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 10
1 <= 'N', ‘M’ <= 10^3
1 <= ‘ARR[i][j]’ <= 10^5

Where ARR[i][j] is the array element in the ith row of the jth column.

Time limit: 1 second

Approaches

01 Approach

We can observe that considering 1 based indexing, the rows having odd index need to be read from left to right, and the rows having index even are read from right to left. Therefore for all the rows we can check this condition and insert the elements in a linear array ANS.

 

Steps:

  • Keep a linear array ANS[] which will store our answer.
  • Traverse the rows of the 2D array. Let i be the current row. (1 <= i <= N)
    • If i is odd
      • We need to traverse this row from j = 1 to M where j denotes the column number.
    • If i is even
      • We need to traverse this row from j = M to 1 where j denotes the column number.

Return the array ANS.