Print matrix in L pattern

We are going to implement an algorithm to print matrix in L pattern in Javascript.

Example

Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

Output:
1
5
9
13
17
18
19
20
2
6
10
14
15
16
3
7
11
12
4
8

/* How it works
First
1 
5 
9 
13 
17 18 19 20

Second
2 
6 
10 
14 15 16

Third
3 
7 
11 12

Fourth
4
8
*/

Implementation

  • We are going to loop continuously until rows and columns of given matrix are printed.
  • With each iteration we will increment the column and reduce the rows.
  • Everything will be written in ES6.
let printMatrixInLShape = (arr, m = arr.length, n = arr[0].length) => {  
  //Initialize the current row and column to zero
  let row = 0;
  let col = 0;

  //Loop until m and n are greater than 0
  while(row < m && col < n){
  
  //print the cols
  for(let a = row; a < m; a++){
    console.log(arr[a][col]);
  }
  col++;  //increment the col
  
  //print the rows
  for(let a = col; a < n; a++){
     console.log(arr[m-1][a]);
  }
  m--;    //reduce the row
     
 }
}         
Input:
printMatrixInLShape([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]);

Output:
1
5
9
13
17
18
19
20
2
6
10
14
15
16
3
7
11
12
4
8

We are using ES6 function to assign the value of left parameter to right parameter (arr, m = arr.length, n = arr[0].length)

Time complexity: O(m * (m + n)) or O(n * (m + n)).

Space complexity: O(1).

Time and Space complexity

  • We are going to loop until m is not zero and col is not equal to n which ever is shorter i.e O(m) or O(n). We will be printing rows and columns one after another in O(m + n), so Time complexity is O(m * (m + n)) or O(n * (m + n)).
  • Wea are using constant space, so Space complexity is O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *