Ninja And Matrix

Easy
0/40
Average time to solve is 15m
profile
Contributed by
1 upvote
Asked in companies
PhonePeVir Softech

Problem statement

Ninja loves patterns and visuals and recently he learned about 2-dimensional matrices now he wants to use his pattern skills on it. He has been provided with a 2-dimensional matrix with a size of ‘N’x’N’ and he wants to print the matrix in a snake pattern. Formally speaking he wants to print every odd indexed row in reverse order(0-indexed) and even indexed row as it is on a single line.

EXAMPLE:
Input: 'N' = 2, ‘MAT’ = [[1, 2], [5, 6]]

Output: 1 2 6 5

 So the first row will be printed as it is and the second row will be printed in reverse order.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

For each test case, the first line will contain a single integer 'N', the size of the matrix ‘Mat’, and then the next ‘N’ lines will contain ‘N’ integers representing the matrix elements.
Output format :
For each test case, print the matrix in a specified manner on a new line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 10
1 <= 'N' <= 10^3
1 <= ‘MAT[i]’ <= 10^9

Time Limit: 1 sec
Sample Input 1 :
2
3
1 2 3
4 5 6
7 8 9
2
5 10
20 15
Sample Output 1 :
1 2 3 6 5 4 7 8 9 
5 10 15 20    
Explanation Of Sample Input 1 :
For the first case:
The first row will be printed as it is and the second row will be printed in reverse order.

For the second case:
Similarly as for test 1.
Sample Input 2 :
2
1
1
2
4 4
6 6
Sample Output 2 :
1
4 4 6 6 
Hint

Can you think of something like an even and odd row?

Approaches (1)
Naive

For each row, if the row is oddly indexed(0-indexed) then print it in reverse order or you can reverse the row, and then you can print it.

 

Algorithm :  

 

  • Initialize a vector named ‘ANS’.
  • For each row from 0 <= row <= ‘N’-1:-
    • If row %2 = 1 :-
      • Reverse the current row.
    • Push every element of the current row into vector ‘ANS’.
  • Return vector ‘ANS’.
Time Complexity

Time Complexity : 

 

O(N*N), Where ‘N’ is the number of rows and columns.

 

As we are traversing the whole matrix of size ‘N’*’N’.

Space Complexity

Space Complexity:

 

O(1).

 

As we are using no extra space.

Code Solution
(100% EXP penalty)
Ninja And Matrix
Full screen
Console