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.
  • From the last element go to the right till we get the padded elements.
  • From the last element go up till we get the padded elements.
  • From the last element go to the left until you get the element you started with (but do not take that element).

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.

Code:-

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

cloud challenges

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Samarth Sewlani

Samarth Sewlani

More from Medium