Matrix Layer Rotation Hackerrank Problem

Task:- Given a 2D matrix of dimensions m,n and integer r. Rotate each layer of matrix ‘r’ times in an anti-clockwise direction.

Rotation of 4x5 matrix is as shown below:

Image from HackerRank

Approach:- First take each layer of the matrix and then rotate that ‘r’ times clockwise. After doing this for each layer put all the elements in their required place.

1) Create a function which takes a list(or array) and ‘r’ as parameters and returns a list rotated ‘r’ times clockwise.

2) Take each layer in the matrix and pass this layer to the above rotate function.

3) Assign the updated(rotated by layers) elements to the matrix.

1] The function rotate takes ‘lst’ and ‘r’ as parameters. This can be done by concatenating two arrays/lists. The first list contains all the elements from index (length-r) to the last index and the second list contains elements from starting index to the elements before index (length-r) where length→ length of ‘lst’.

2] To take each layer of matrix:

We can observe that for each layer we leave one row and one column as padding from the previous layer. So for the first layer there is no padding so we take all the outermost elements, then for the second layer we leave all those elements and then take the remaining layer.

This can be done by following below steps:

  • Start from the left and go down till the padded elements.

We can observe that the number of layers (or depth) would be given by : min (m,n) / 2

Where m & n are dimensions of the matrix. This formula can be obtained by manually taking few values of m&n and checking the number of layers.

3] To assign the elements traverse the matrix in similar fashion but this time instead of taking the elements we have to assign the new values which we stored in the ‘layers’ list.